Python Dictionary

Spread the love

What is Dictionary in Python ?

A Dictionary in Python is a collection of key-value pairs. Each key in a dictionary is connected to a value and you can use a key to access the value associated with that key. A key’s value can be a number, a string, a list or even a dictionary.

How to Create a Dictionary in Python ?

To create a dictionary in python we use curly braces with series of key-value pairs inside the braces.

Let’s say you want to store a persons details. For that you can use a dictionary.

In [1]: person = {'Name': 'Noah', 'Age': 25, 'Location': 'New York'}

Every key in a dictionary is connected to it’s value by a colon and individual key-value pairs are separated by commas.

How to access values in a Dictionary ?

To get a value associated with a key, first provide the name of the dictionary then provide the key inside the square brackets.

Let’s say we want to know the Location of Noah, all we have to do is simply ask for his location like this.

In [2]: person['Location']
Out[2]: 'New York'

Similarly, we can also get his Name and Age.


In [3]: person['Name']
Out[3]: 'Noah'

In [4]: person['Age']
Out[4]: 25

How to add a new Key-Value pair in a dictionary ?

To add a new key-value pair in a dictionary, you have to give the name of the dictionary followed by the key in square brackets and new value in the right hand side of the equal sign.

To add the profession of Noah, you have to write


In [5]: person['Profession'] = 'student'

In [6]: person
Out[6]: {'Name': 'Noah', 'Age': 25, 'Location': 'New York', 'Profession': 'student'}

How to create an Empty Dictionary ?

Sometimes you may want to start with an empty dictionary then later add key-value pairs as you progress. To create an empty dictionary, we use an empty sets of braces, then we add each key-value pairs.


In [7]: person = {}

In [8]: person['Name'] = 'Noah'

In [9]: person['Age'] = 25

In [10]: person['Location'] = 'New York'

In [11]: person['Profession'] = 'student'

In [12]: person
Out[12]: {'Name': 'Noah', 'Age': 25, 'Location': 'New York', 'Profession': 'student'}

How to modify the values of a dictionary ?

To modify a dictionary, give the name of the dictionary with the key in square brackets and the new value you want to associate with the key.

Let’s say you want to change the profession of Noah from student to Data scientist.


In [13]: person['Profession'] = 'Data Scientist'

In [14]: person
Out[14]: 
{'Name': 'Noah',
 'Age': 25,
 'Location': 'New York',
 'Profession': 'Data Scientist'}

How to remove key-value pairs in a Dictionary ?

To delete a key-value pair from a dictionary you can use the del statement.

Let’s say that I want to remove the profession of Noah.

In [15]: del person['Profession']

In [16]: person
Out[16]: {'Name': 'Noah', 'Age': 25, 'Location': 'New York'}

How to Loop through a Dictionary ?

A dictionary can contains a single key-value pair or millions of key-value pairs. So Python let’s you loop through a dictionary. And there are various ways to loop through a dictionary. Let’s look at them.

Looping through all key-value pairs

To loop through a dictionary in Python, you can use a for loop.

Let’s say I want to get all the information we have stored about Noah.

In [17]: for key, value in person.items():
    ...:     print("\nKey: ", key)
    ...:     print("Value: ", value)
    ...:     

Key:  Name
Value:  Noah

Key:  Age
Value:  25

Key:  Location
Value:  New York

To hold the key and the value in each key-value pairs we used two variables in the for loop. You can name these variables anything you want, It’s completely up to you. But try to be informative, which will help others to understand it better. Then in the end of the for loop we write the name of the dictionary followed by the item method which gives the list of key and value in pairs of the dictionary. Then in the body of the for loop we use two print statements to print the key and value of each key-value pair in the dictionary. The “\n” in the first print statement ensures that a new blank line is added before each key-value pair in the output.

Although here we get the key-value pairs in order in the output. It might not always happens as Python does not care about the order in which you stored the key-value pairs in a dictionary. It only care about the individual connection between each key and value of a pair.

Looping through all keys in a dictionary –

If you only want to loop through all the keys of a dictionary then you can use the keys() method.


In [18]: for key in person.keys():
    ...:     print(key)
    ...:     
Name
Age
Location

The first line says pull all the keys from the dictionary and store then in the key variable one at a time. Then in the body of the loop we just print it.

Looping through the keys is the default behavior when we loop through a dictionary. So to loop through a dictionary we can also write.

In [19]: for key in person:
    ...:     print(key)
    ...:     
Name
Age
Location

Looping through all the values in a dictionary –

To loop through all the values in a dictionary we use the values() method.

In [20]: for value in person.values():
    ...:     print(value)
    ...:     
Noah
25
New York

Nesting –

Sometimes you may want to store dictionaries in a list or a list as a value inside a dictionary or a dictionary inside a dictionary. This is called nesting. Let’s see how to use nesting in dictionary.

A list of Dictionaries –

The person dictionary contains the information about only one person. If we want to to store information of multiple persons then we can create multiple separate dictionaries for each persons and put them all inside a list.

In [21]: person1 = {'Name': 'Noah', 'Age':25, 'Location': 'New York'}

In [22]: person2 = {'Name': 'Sarah', 'Age': 23, 'Location': 'California'}  

In [23]: person3 = {'Name': 'Emma', 'Age': 23, 'Location': 'New York'}

In [24]: persons = [person1, person2, person3]

First we created 3 dictionaries, 0ne for each persons and then put them all inside a list.

Now, we can loop through each item in the list to get each persons information.

In [25]: for person in persons:
    ...:     print(person)
    ...:     
{'Name': 'Noah', 'Age': 25, 'Location': 'New York'}
{'Name': 'Sarah', 'Age': 23, 'Location': 'California'}
{'Name': 'Emma', 'Age': 23, 'Location': 'New York'}

Let’s say for some reasons you want to store the locations of each persons inside another list, you can do like this.

In [26]: # create empty dictionary to store locations

In [27]: locations = []

In [28]: for person in persons:
    ...:     locations.append(person['Location'])
    ...:     

In [29]: locations
Out[29]: ['New York', 'California', 'New York']

First we loop through each persons then we accessed the locations of each persons and kept adding them in the locations list.

A List inside a dictionary –

Sometimes you may want to put a list inside a dictionary. We can reformat the previous example like this.

In [32]: persons = {'Name': ['Noah', 'Sarah', 'Emma'],
    ...:         'Age': [25, 23, 23],
    ...:         'Location': ['New York','California','New York']}

In [33]: persons
Out[33]: 
{'Name': ['Noah', 'Sarah', 'Emma'],
 'Age': [25, 23, 23],
 'Location': ['New York', 'California', 'New York']}

Now, if I want to print each persons name, age, and location, I have to write


In [34]: for i in range(len(persons['Name'])):
    ...:     print("\nStudent Number:", i + 1)
    ...:     print("Name:", persons['Name'][i])
    ...:     print("Age:", persons['Age'][i])
    ...:     print("Location:", persons['Location'][i])
    ...:     

Student Number: 1
Name: Noah
Age: 25
Location: New York

Student Number: 2
Name: Sarah
Age: 23
Location: California

Student Number: 3
Name: Emma
Age: 23
Location: New York

First, we need to figure out how many students are there. So we used len(persons[‘name’]) which gives us the length of the list in the name key. We could have used any key here. Then we used range which produced a list of numbers from 0 to 2 (0, 1, 2) as we have 3 students. Next in the body of the for loop we accessed each keys for name, age and locations like persons[‘name’] for name key and as the values of each keys in the dictionary is a list we used list accessing to get the first, second and third students names like persons[‘name’][0], persons[‘name’][1], persons[‘name’][2]. Similarly we accessed the age and locations of each students.

A dictionary in a dictionary –

You can also nest a dictionary inside a dictionary. Let’s say we have the dictionary in this format.

In [35]: persons = {1: {'Name':'Noah', 'Age':25, 'Location':'New York'},
    ...:             2: {'Name':'Sarah', 'Age':23, 'Location':'California'},
    ...:             3: {'Name':'Emma', 'Age': 23, 'Location':'New York'}}

Now, to print each students names we can write.

In [36]: for key, value in persons.items():
    ...:     print("\nStudent Number:", key)
    ...:     print("Name:", value['Name'])
    ...:     print("Age:", value['Age'])
    ...:     print("Location:", value['Location'])
    ...:     

Student Number: 1
Name: Noah
Age: 25
Location: New York

Student Number: 2
Name: Sarah
Age: 23
Location: California

Student Number: 3
Name: Emma
Age: 23
Location: New York

Here, we use the dictionaries items method to get the keys and values of nested dictionaries. The key contains the student numbers and the values contains each students information in a dictionary. To get the name of a student we used value[‘name’] as value is a dictionary and we can access the value of a key like this dictionary_name[‘key’]. Similarly we get the Age and locations of each students.

Although dictionary inside a dictionary is a little bit complicated, with practice you will get better. If you like this post then please share it with others and subscribe to our blog for more posts like this.

Leave a Reply