Dict: Associative Array

06_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).

Python Dictionaries | python.org

In [1]:
my_dictionary = {
    "alpha": 1,
    "beta": 2,
    "gamma": 3,
    "zeta": 42,
}

print(my_dictionary)
{'alpha': 1, 'beta': 2, 'gamma': 3, 'zeta': 42}

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.

In [2]:
a = my_dictionary.get("alpha")
print("a is", a)
a is 1

or…

In [3]:
b = my_dictionary["beta"]
print("b is", b)
b is 2

Adding an item:

In [4]:
my_dictionary["delta"] = 4
print(my_dictionary)
{'alpha': 1, 'beta': 2, 'gamma': 3, 'zeta': 42, 'delta': 4}

Removing an item:

In [5]:
z = my_dictionary.pop("zeta")

print("z is", z)
print(my_dictionary)
z is 42
{'alpha': 1, 'beta': 2, 'gamma': 3, 'delta': 4}

Printing the Keys and Values:

In [6]:
dict_keys = my_dictionary.keys()
dict_vals = my_dictionary.values()

print(dict_keys)
print(dict_vals)
dict_keys(['alpha', 'beta', 'gamma', 'delta'])
dict_values([1, 2, 3, 4])

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

In [7]:
for key in my_dictionary.keys():
    print(key)
alpha
beta
gamma
delta

Printing Values Only

In [8]:
for value in my_dictionary.values():
    print(value)
1
2
3
4

Printing Keys and Values with Formatting

In [9]:
for key, val in my_dictionary.items():
    print(f"{key}: {val}")
alpha: 1
beta: 2
gamma: 3
delta: 4

Dictionary Comprehension

In [10]:
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)
{'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5}