How To Work With Python Dictionary – Tutorial With Code Examples

This Tutorial Explains How to Create a Python Dictionary Along With Methods to Access, Add, Modify, Delete & Iterate Through Data Stored in a Dictionary:

In this Python Training For All, we had a look at the most commonly asked Python Interview Questions. This tutorial explains all about Dictionaries in Python along with simple examples.

A Dictionary in Python is a collection of Key-Value pairs. Each Key is connected to value and you can use the Key to access the value associated with that Key.

A Key can be a number/string and the Key’s value can be a number, a string, a list or even another Dictionary.

Dictionaries in Python

A real-time example of a Dictionary can be found at the end of any book, where topics are given according to the page number. Here, a page number can be considered as a Key and the topics can be considered as values.

How To Create A Dictionary In Python?

Python Dictionary is created in the following manner:

Students = {'001':'John','002':'Jane','003':'Rahul','004':'Riya'}

Every Key is connected to its value by a colon and the individual Key-value pairs are separated by commas. You can store any number of key-value pairs in a Dictionary.

How To Access Values In A Python Dictionary?

To access a value associated with the Key in Dictionary, you need to give the name of the Dictionary followed by its Key in square brackets.

Input:

Students = {'001':'John','002':'Jane','003':'Rahul','004':'Riya'}
print(Students['001'])

Output:

John

You can access multiple values in Dictionary in the following manner:

Input:

Students = {'001':'John','002':'Jane','003':'Rahul','004':'Riya'}
print(Students['001'],Students['002']) # Accessing multiple values

Output:

John Jane

How To Add New Key-Value Pairs In Dictionary?

Dictionaries are dynamic, and we can add any number of new Key-value pairs to an existing dictionary.

Let us add 2 new students to the existing Dictionary.

Students = {'001':'John','002':'Jane','003':'Rahul','004':'Riya'}

                        Students['005']='Shane'
                        Students['006']='Melisa'

Thus once we give the following Input:

Students = {'001':'John','002':'Jane','003':'Rahul','004':'Riya'}

                        Students['005']='Shane'
                        Students['006']='Melisa'
print(Students)

The Output will be:

{‘001′:'John','002′:'Jane','003′:'Rahul','004′:'Riya','005′:'Shane','006′:'Melisa'}

Now, we can also access the newly added key-value pairs:

Input:

print(Students['005'])

Output:

Shane

How To Modify Values In Dictionary?

To modify a value in a dictionary, we need to give the name of the dictionary followed by the Key in square brackets and then the new value associated with that Key.

Suppose in the following Dictionary:

Students = {'001':'John','002':'Jane','003':'Rahul','004':'Riya','005':'Shane','006':'Melisa'}

We want to change the value associated with key 001 to David, then we can simply do it in the following manner.

Students['001'] = 'David'

On running the program:

Input:

Students = {'001':'John','002':'Jane','003':'Rahul','004':'Riya','005':'Shane','006':'Melisa'}
Students['001'] = 'David'
print(Students['001'])

Output:

David

How To Delete Key-value Pairs In A Dictionary?

In case you no longer require a piece of information stored in a Dictionary, then you can simply remove or delete that piece of information from the Dictionary using del command.

Students = {'001':'John','002':'Jane','003':'Rahul','004':'Riya','005':'Shane','006':'Melisa'}

For Example, we want to remove – ‘004':'Riya' from the above dictionary, then we can simply do it by the following command:

del Students['004']

Now, On giving the Input:

Students = {'001':'John','002':'Jane','003':'Rahul','004':'Riya','005':'Shane','006':'Melisa'}
del Students['004']
print(Students)

The Output will be:

{‘001': ‘John','002′: ‘Jane','003′: ‘Rahul','005′: ‘Shane', ‘006': ‘Melisa'}

Note: Dictionaries do not follow any particular sequence. Thus when you run the program, you may get the output in different sequences.

For Example,

{‘005': ‘Shane', ‘003': ‘Rahul', ‘002': ‘Jane', ‘006': ‘Melisa', ‘001': ‘John'}

Exercise:

Write a program to create a Dictionary of Employees that includes their ID and Name. Later add some Employees, and update the information of one of the employees and Delete the information of the employee who leaves the organization.

# Creating a Dictionary of Employees

Employees = {
                               'Emp_001': 'Rahul Khanna',
                               'Emp_002': 'Surbhi Jain',
                                'Emp_003': 'Maria Sharapova'
                           }
    print(Employees)

# Fetching the information of 2nd Employee

print(Employees['Emp_002'])

# Adding two more Employees

Employees['Emp_004']='Ricky Martin'
Employees['Emp_005']='Sanaya Malhotra'

# Print Dictionary to check if Employees are updated

print(Employees)

# Updating information of Emp_003 – Changing name to Maria Curie

Employees['Emp_003']='Maria Curie'

# Verifying updated information

print(Employees['Emp_003'])

# Delete Employee 1

del Employees['Emp_001']
print(Employees)

Output:

{‘Emp_001': ‘Rahul Khanna', ‘Emp_002': ‘Surbhi Jain', ‘Emp_003': ‘Maria Sharapova'}

Surbhi Jain

{‘Emp_001': ‘Rahul Khanna', ‘Emp_002': ‘Surbhi Jain', ‘Emp_003': ‘Maria Sharapova', ‘Emp_004': ‘Ricky Martin', ‘Emp_005': ‘Sanaya Malhotra'}

Maria Curie

{‘Emp_002': ‘Surbhi Jain', ‘Emp_003': ‘Maria Curie', ‘Emp_004': ‘Ricky Martin', ‘Emp_005': ‘Sanaya Malhotra'}

Iterate Through Python Dictionary

As Dictionaries can contain a large amount of data, Python lets you loop through the Dictionary. Dictionaries can store information in a variety of ways, hence you can loop through the Dictionary in different ways. You can loop through the Key-value pairs in a Dictionary, through the keys or its values.

  • How to loop through the Key-Value pairs in Dictionary?

Let us take an example of a new Dictionary that is used to store information about Football players, their name, height, and weight.

Player_1 = {
                       'Name': 'Peter',
                       'Height' : '5ft 9inch',
                       'Weight' : '82 Kg'
                      }

As you know, you can access a single piece of information based on what you have learned so far, But how to access all the information at once? You can use for loop to loop through the Dictionary.

 for key,value in Player_1.items():
 print("\n Key:" +key)
 print("Value:" +value)

As you can see to write a for loop for the Dictionary, you need to create two variables that will hold a key and value respectively. Here we have taken the variable names as Key, and Value but we could have taken any variable name like k, v.

There will not be any difference in the output if we write our code in the following way:

for k,v in Player_1.items():
 print("\n Key:" +k)
print("Value:" +v)

The next part of the For statement includes the name of the Dictionary followed by the method items(), that returns a list of the key-value pairs. The For loop then stores each of these pairs in the two variables provided. In the preceding example, we use the variables to print each key, followed by the associated value.

The “\n” in the first print statement ensures that a blank line is inserted before each Key-value pair in the output:

Key:Name
Value:Peter

Key:Height
Value:5ft 9inch

Key:Weight
Value:82 Kg

  • How to loop through all the keys in the Dictionary?

To loop through all the keys in a Dictionary, you can use the Keys method. Let us loop through all the Keys in the following Dictionary.

Player_1 = {
                         'Name': 'Peter',
                         'Height' : '5ft 9inch',
                          'Weight' : '82 Kg'
                    }
for attributes in Player_1.keys():
print(attributes.title())

The statement for attributes in Player_1.keys() tells Python to pull all the keys from the dictionary Player_1 and store them one at a time in the variable name.

The program produces the following output:

Name
Height
Weight

If we give our input in the following manner:

 for attributes in Player_1:
print(attributes.title())

There will not be any difference in the output as looping through the keys is the default behavior of the Dictionary.

  • How to loop through all the values in the Dictionary?

If your purpose is to get all the values from a dictionary then you can use the values method.

Let’s say in the following Dictionary, we just want to fetch the student's name.

Students = {
'001':'John',
'002':'Jane',
'003':'Rahul',
'004':'Riya'
}

for name in Students.values()
print(name.title())

The for statement here pulls each value from the dictionary and stores it in the variable – name. The Print statement prints all the names and we get the following output:

John
Jane
Rahul
Riya

Nesting In Python Dictionaries

Sometimes you may want to store a set of Dictionaries in a list or a list of items as a value in a Dictionary and this is called Nesting. You can nest a set of Dictionaries inside a list, a list of items inside a Dictionary or even a Dictionary inside another Dictionary.

Nesting is a powerful feature, let us demonstrate that using examples.

List Of Dictionaries

Let us take an example of the Player Dictionary that contains a variety of information about one Player, but it has no room to store information about more number of players.

We can simply create 3 dictionaries each representing a different player. We pack each of these Dictionaries into a list called Players. Finally, we can loop through the list and printout each of them.

Player_1 = {
                           'Name' : 'Peter',
                           'Height' : '5ft 9inch',
                           'Weight' : '72 Kg'
                    }
     Player_2 = {
                           'Name' : 'John',
                           'Height' : '5ft 7inch',
                           'Weight' : '82 Kg'
                    }
     Player_3 = {
                           'Name' : 'Rahul',
                           'Height' : '5ft 11inch',
                           'Weight' : '65 Kg'
                    }

     Players = [Player_1,Player_2,Player_3]
     for Player in Players:
      print(Player)

Output:

{‘Name': ‘Peter', ‘Height': ‘5ft 9inch', ‘Weight': '72 Kg'}
{‘Name': ‘John', ‘Height': ‘5ft 7inch', ‘Weight': '82 Kg'}
{‘Name': ‘Rahul', ‘Height': ‘5ft 11inch', ‘Weight': '65 Kg'}

It’s common to store a number of Dictionaries in a list when each Dictionary contains several kind of information about one object.

For Example, you might create a Dictionary for each user on a website, and store the individual Dictionaries in a list called users. All the Dictionaries in the list should have an identical structure so that you can loop through the list and work with each Dictionary object in the same way.

Dictionary In A Dictionary

You can nest a Dictionary inside another Dictionary, but when you do that, your code can get complicated quickly. For Example, if you have several users for a website, each with a unique username, then you can use the username as the keys in a Dictionary.

You can then store information about each user by using a Dictionary as the value is associated with their username. In the following listing, we store three pieces of information about each user i.e. their first name, last name, and location. We will access this information by looping through the usernames and the Dictionary of information associated with each username.

users = {
                'Rahul99': {
                'first': 'Rahul',
                'last': 'Jain',
                'location': 'New Delhi',
                     },

     'Jane19': {
     'first': 'Jane',
     'last': 'Aniston',
     'location': 'New York',
      },

      }
      for user, user_info in users.items():
      print("\nUsername = "+user)
      print("First name = "+user_info['first'])
      print("Last name = "+user_info['last'])
      print("Location = "+user_info['location'])
      

We first define a Dictionary called users with two Keys: one each for the usernames ‘Rahul99' and ‘Jane19'. The value associated with each key is a Dictionary that includes each user’s first name, last name, and location. We loop through the user's Dictionary.

Python stores each Key in the variable username and the Dictionary associated with each username goes into the variable user_info. Once inside the main Dictionary loop, we print the username.

We start accessing the inner Dictionary. The variable user_info, that contains the Dictionary of user information, has three keys i.e. ‘first', ‘last', and ‘location'. We use each key to generate the first name, last name, and the location for each user, and then print a summary of what we know about each user.

The output of the program will be:

Username = Rahul99
First name = Rahul
Last name = Jain
Location = New Delhi

Username = Jane19
First name = Jane
Last name = Aniston
Location = New York

Exercise:

Write a Dictionary called cities. Use the names of three cities having one wonder of the world as the keys in your Dictionary. Create a Dictionary of information about each city and include the country that the city is in, its approximate population, and the name of the Wonder.

The Keys for each city’s Dictionary should be something like country, population, and wonder. Print the name of each city and all the information that you have stored about it.

# Creating a Dictionary in Dictionary

Cities = {
       'Newyork':  {
                                'Country' : 'USA',
                                'population' : '700k',
                                'wonder' : 'Statue of Liberty'
                              },
     'Agra': {
                              'Country' : 'India',
                               'population' : '300k',
                               'wonder' : 'Taj Mahal'
                               },
     'Paris': {
                               'Country' : 'France',
                                'population' : '500k',
                                'wonder' : 'Eiffel Tower'
                               }
                           }

# Looping through all the values in Dictionary

 for City, cities_info in Cities.items():
                 print("\nCity = " +City)
                 print("\tCountry="+cities_info['Country'])
                 print("\tPopulation=" +cities_info['population'])
                 print("\tWonder="+cities_info['wonder'])

Output:

City = Newyork
Country=USA
Population=700k
Wonder=Statue of Liberty

City = Agra
Country=India
Population=300k
Wonder=Taj Mahal

City = Paris
Country=France
Population=500k
Wonder=Eiffel Tower

Conclusion

In this tutorial, we learned how to define a dictionary in Python and how to work with the information stored in a Dictionary. We also learned how to access and modify individual elements in a Dictionary.

Then we explored how to loop through Dictionary, nest multiple Dictionaries in the list and nest Dictionary inside a Dictionary.

Happy Reading!!

We hope you enjoyed the entire series of Python tutorials!! We are sure that these Python tutorials would be a complete guide for Beginners!!

PREV Tutorial | First Tutorial