9  Dictionaries

These are collection of items arranged as a key-value pair. A dictionary is represented by {} and there is a dict keyword in python to assign dictionary data type. The value for a particular key in a dictionary can be accessed by specifing the key within [] after the dictionary name.

colors = {'blue':'sky', 'white':'milk', 'red':'rose'}
print(colors)
print(type(colors))
print(colors["red"])
{'blue': 'sky', 'white': 'milk', 'red': 'rose'}
<class 'dict'>
rose

An alternate way to initialize a dictionary is by using the dict keyword. In the code below, notice the differences in how the key-value pairs are specified while inititalize a dictionary with the dict keyword. The len function with a dictionary as an argument returns the total number of key-value pairs in that dictionary.

colors_new = dict(blue="ink", white="paper")
print(colors_new)
print(len(colors_new))
{'blue': 'ink', 'white': 'paper'}
2

The values in a dictionary could any data type such as string, integer, list or even dictionary. On the other hand, keys can only be immutable data types such as string, integer or tuple.

# a dictionary with numbers as keys
Numbers = {1:"one", 2:"two"}
print(Numbers[1])
one
# a dictionary with list as values
stationery = {"pens":["ball", "fountain"], "paper":["A4", "A3", "A2"]}
print(stationery["paper"])
print(stationery["paper"][1])
['A4', 'A3', 'A2']
A3

9.1 Iterating through dictionaries

The keys and values functions can be used to get all keys and all values as a list, respectively. To get all the keys of a dictionary as list, the list function with dictionary as an argument can also be used.

print(stationery.keys())
print(stationery.values())
print(list(stationery))
dict_keys(['pens', 'paper'])
dict_values([['ball', 'fountain'], ['A4', 'A3', 'A2']])
['pens', 'paper']

The items function comes handy for iterating through the content of the dictionary. This function return the key-value pairs as a tuple and all these key-value tuples are arranged in a list. We can then iterate through this list to access the key-value pairs. Note that while iterating through this list, two variables need to be specified in the for loop which would be mapped to the key and value in the tuple, respectively.

print(stationery.items())
dict_items([('pens', ['ball', 'fountain']), ('paper', ['A4', 'A3', 'A2'])])
for k1, v1 in stationery.items():
    print(f"The key is {k1} and its value is {v1}")
The key is pens and its value is ['ball', 'fountain']
The key is paper and its value is ['A4', 'A3', 'A2']

Just like lists, we can modify the contents of a dictionary by adding or removing key-value pairs. When adding a key-value pair if the key doesn’t exists then a new key would be created while if the key is already present then its value would be modified.

Numbers = {1:"one", 2:"two"}
print(Numbers)
Numbers[3] = "three"
print(Numbers)
Numbers[2] = "dos"
print(Numbers)
{1: 'one', 2: 'two'}
{1: 'one', 2: 'two', 3: 'three'}
{1: 'one', 2: 'dos', 3: 'three'}
del(Numbers[2])
print(Numbers)
{1: 'one', 3: 'three'}

9.2 Dict comprehensions

Yet another way to initialize a dictionary is via dict comprehensions. Just like list comprehensions, here a dictionary is created by processing elements in a list. The code below creates a dictionary with numbers and their squares as key-value pairs.

new_dict = {x: x**2 for x in range(1,5)}
print(new_dict)
{1: 1, 2: 4, 3: 9, 4: 16}

Quiz: Given a dictionary: d1 = {1:“one”, 2:“two”, 3:“three”} Write a code to check if “two” is present 1) as a key and 2) as a value.

Show answer
d1 = {1:"one", 2:"two", 3:"three"}
if("two" in d1.keys()):
    print('"two" is a key in d1')
if("two" in d1.values()):
    print('"two" is a value in d1')
    
# Alternate solution
print("Alternate solution")
for k1,v1 in d1.items():
    if("two" == k1):
        print('"two" is a key in d1')
    if("two" == v1):
        print('"two" is a value in d1')
"two" is a value in d1
Alternate solution
"two" is a value in d1