Dictionaries
A dictonary represents a mapping from keys to values
# A dictonary represents a mapping ...
# from keys to values
#
# In a list, the index have to be integer ...
# in a dictionary it can be any type.
# Create a dictionary using dict()
D = dict()
D["one"] = "uno"
assert D.get("one") == "uno"
assert D.get("one") != None
assert D.get("one") != "one"
# Creates a dictionary using {}
D = {
"one": "uno",
"two": "dos",
"three": "tres",
}
assert D.get("two") == "dos"
assert D["two"] == "dos"
# in operator
assert "one" in D
assert ("dos" in D) == False
assert ("two" in D) == True
# Loop
for v in D.values():
print(v)
# uno
# dos
# tres
for k in D.keys():
print(k)
# one
# two
# three
Histogram
Suppose you have a string and you want to count how many times each letter appears.
# Histogram
#
# How many times each letter appears
# To get a value use get(key, default) method
#
# Use for statement to traverse the keys of the dictionaries.
# The keys are in no order.
# string histogram
def histogram(str):
dictionary = dict()
for ch in str:
if ch not in dictionary:
dictionary[ch] = 1
else:
dictionary[ch] += 1
return dictionary
assert histogram("google") != {}
assert histogram("google") != {'g': 0, 'o': 0, 'l': 0, 'e': 0}
assert histogram("google") == {'g': 2, 'o': 2, 'l': 1, 'e': 1}
# get(key, default)
assert histogram("yahoo").get('o') == 2
assert histogram("yahoo").get('o', 0) == 2
# foreach key, print value
h = histogram("google")
for k in h:
print(k + ": " + str(h[k]))
# g: 2
# o: 2
# l: 1
# e: 1
# invert histogram - to map the frequencies to letters
def invert_histogram(d):
dictionary = dict()
for key in d:
value = d[key]
if value not in dictionary:
dictionary[value] = [key] # new row list
else:
dictionary[value].append(key) # add to row list
return dictionary
h = invert_histogram(histogram("google"))
for k in h:
print(k, h[k])
# 2 ['g', 'o']
# 1 ['l', 'e']
Hash
The dictionary's keys have to be hashable.
# Dictionary hashes:
#
# A hash is a function that takes a value (on any kind) and returns an integer.
# Dictionaries use these integers to store and look up key-value pairs.
#
# The keys have to be hashable.
# Mutable types like lists are not hashable.
dict = {}
dict["one"] = 1
dict[1] = "abc"
print(dict) # {'one': 1, 1: 'abc'}
list = [1, 2]
# dict[list] = 3
# TypeError: unhashable type: 'list'
Last update: 410 days ago