Dict: Associative Array
Dictionary: Ordered Associative Array¶
Dictionaries are also known as hashtables. The keys of a dictionary must be hashable. The values may be any type of object (including lambda, list, string or even another dictionary).
my_dictionary = {
"alpha": 1,
"beta": 2,
"gamma": 3,
"zeta": 42,
}
print(my_dictionary)
Reading an item:¶
While the first example below is a bit more Pythonic, the second one is far more common. The .get()
method will return None
if the key does not exit in the dictionary. The second example will raise a KeyError instead.
a = my_dictionary.get("alpha")
print("a is", a)
or…
b = my_dictionary["beta"]
print("b is", b)
Adding an item:¶
my_dictionary["delta"] = 4
print(my_dictionary)
Removing an item:¶
z = my_dictionary.pop("zeta")
print("z is", z)
print(my_dictionary)
Printing the Keys and Values:¶
dict_keys = my_dictionary.keys()
dict_vals = my_dictionary.values()
print(dict_keys)
print(dict_vals)
Dictionary Iteration¶
The following is only possible because dictionaries are now ordered – since Python 3.6. They maintain the order you give them, if you add an item, it is added to the end of the dictionary. In previous versions of Python, dictionaries were not ordered, in fact – they were randomized.
Printing Keys Only
for key in my_dictionary.keys():
print(key)
Printing Values Only
for value in my_dictionary.values():
print(value)
Printing Keys and Values with Formatting
for key, val in my_dictionary.items():
print(f"{key}: {val}")
Dictionary Comprehension¶
char = ('a', 'b', 'c', 'd', 'e', 'f')
nums = ( 0, 1, 2, 3, 4, 5 )
dict_comp = {k: v for k, v in zip(char, nums)}
print(dict_comp)