Chapter 8 Dictionary

Dictionaries are useful data structures for solving real-life problems. Here is an example.

Let us say you want to store the ages of three of your friends (John - 15 years old, Jeremy - 14 years old and Jessica - 16 years old). You need to store both the names and the ages, and therefore you can potentially use two lists.

names = ["John", "Jeremy", "Jessica"]
ages = [15, 14, 16]

Here is the difficulty you will encounter. If someone asks you to find the age of Jessica, you have to go over the names list to find the position of Jessica (2) and then go to ages list to print ages[2]. This may be doable with 3 friends, but imagine a social media website trying to do this repeatedly for 100 million users.

Python has a solution called dictionary, which works like this -

ages = {"John": 15, "Jeremy": 14, "Jessica": 16}

print(ages["Jessica"])

You will notice that if a name is not in the dictionary, the program crashes with an error message. To avoid that, you can use the following syntax -

if "Mike" in ages:
   print(ages["Mike"])

You can also add more names to the list or update any existing data -

ages["Mike"] = 17
ages["John"] = ages["John"] + 1
print(ages)

Dictionary loses the sense of order

Keyword Action
in checks if an element is in a list or dictionary
del deletes an element from a list or dictionary

8.1 Dictionary vs List

Figure Figure

Try -

age={}
age['john']=12
age['paul']=77

print(age['john'])
print(age)

8.2 Keyword - in

age={}
age['john']=12
age['paul']=77

print(12 in age)
print('john' in age)

8.3 Keyword - del

The keyword del can be used to remove the members of a dictionary.

age={}
age['john']=12
age['paul']=77

print(age)
del age['john']
print(age)
age={'john':12, 'paul': 77}

age={'john':12, 'paul': 77, 'john': 22}

8.4 Using ‘for’ over a Dictionary

Try -

age = {}
age['john'] = 12
age['paul'] = 77

for key in age:
        print( key )
        print( age[key]+7 )

When ‘for’ is written on a dictionary, the loop variable takes the values of the keys of the dictionary.