This tutorial explains what is a Dictionary in Python and how to work with a Python Dictionary, Nested Dictionary, Dictionary vs Lists, etc:
Just as Lists, Python has another data type called a dictionary which is a bit similar to List, Set, and Tuple.
A Dictionary in Python is a collection of Key-Value pairs. Each Key is connected to a 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.
As we shall see throughout this tutorial, dictionaries are a part of what makes Python so effective and powerful.
=> Check ALL Python Tutorials Here
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 keys and the topics can be considered as values.
What Is A Python Dictionary
Python dictionaries are commonly known as associative arrays, which are abstract data types composed of a collection of (key, value) pairs, such that each possible key appears at most once in the collection.
A dictionary has the below syntax:
{ key1: value1, key2: value2, . . . keyN: valueN }
From the syntax above, we can define a dictionary with a curly brace({}) enclosing one or more comma-separated key-value pairs where a key and its associated value are separated by a colon(:)
Each key of the dictionary is associated with a value where the values need not be hashable, only the keys. An object is hashable if it has a hash value that never changes during its lifetime.
Examples of hashable objects are (strings, bytes, numeric types). Mutable objects like lists, tuples and even dictionaries are not hashable and can’t be used as keys in a dictionary.
Dictionaries Vs Lists
Lists and dictionaries are so common that a program or script without one or both of them may be nearly inconceivable.
Lists and dictionaries share some similar characteristics:
- Are both dynamic i.e. they can grow and shrink at runtime.
- Are both mutable i.e. they can be changed in-place
- They can be contained in each other i.e. dictionary can be contained in lists and vice versa.
Dictionaries differ from lists primarily in the way in which they are structured and how their elements are accessed.
The table below gives some of the differences between a dictionary and a list.
Dictionary | List |
---|---|
Defined with a curly brace({}) enclosing one or more comma-separated key-value pairs where a key and its associated value is separated by a colon(:). | Defined with a square bracket([]) where each item in the list is separated by a comma(,), with the first item at index 0. |
Elements are accessed using keys. | Elements are accessed by their position in the list, using indexing. |
Are unordered sets. | Are ordered sequence of objects. |
Belongs to the built-in mapping type. | Belongs to the built-in sequence type. |
Variations Of Python Dict In The Standard Library
Apart from Python’s general-purpose built-in container dict, Python has specialized mapping types implemented in the collections module. These mapping types were introduced to improve the functionalities of the built-in dict data type.
In this section, we shall summarize the most commonly used mapping types.
#1) Counter
It is a dict subclass that holds an integer count for each key, where the integer count can be any number including zero and negative numbers. They are generally used to count instances of hashable objects(keys).
Counter’s methods and description:
Method | Description |
---|---|
c.element() | Returns an iterator containing all elements repeating each as many times as its count(excluding count less than one) in the Counter object. |
c.most_common([n]) | Returns a list of tuples containing the n most common elements and their counts. If n is not given or None, returns all elements and their counts. |
c.subtract([iterable-or-mapping]) | Deduce elements count from Counter object that matches elements in the iterable or mapping argument. |
Example: In this example, we shall explore the Counter object and its various methods.
# Import Counter from the collections module from collections import Counter def counter_examples(): repeated_letters = 'abdegadlbdaalg' # string to generate count object # Create the counter object from the repeated letters cn = Counter(repeated_letters) print("Counter Object: ", cn) # Display all elements each repeated by their number of count elem = cn.elements() print("All Elements: ", list(elem)) # Get the 2 most common elements and their count com_2 = cn.most_common(2) print("2 Most Common: ", com_2) # Deduce 2 counts of 'a', 2 count of 'd' and 1 count of 'e' sub_map = dict(a=2, d=2, e=1) # create a dictionary containing elements and counts to deduce. cn.subtract(sub_map) print("After Subtraction ", cn) if __name__ == '__main__': counter_examples()
Output
#2) defaultdict
This object creates items on demain whenever a missing key is accessed unlike the built-in dict which raises a KeyError.
It is instantiated with a callable(held in an instance attribute called default_factory) which is used to produce a default value whenever a non-existent key argument is accessed.
Example: Use defaultdict to count the number of occurrence of each letter in the string ‘abdegadlbdaalg’
# Import defaultdict from the collections module from collections import defaultdict def defaultdict_examples(): repeated_letters = 'abdegadlbdaalg' # define our string of letters # Instantiate a defaultdict with callable 'int'. letter_cnt = defaultdict(int) # loop through each letter of the string for letter in repeated_letters: # each letter in the defaultdict is initialized with 0 since the collable is 'int' letter_cnt[letter] += 1 print("Letter Counts: ",letter_cnt) if __name__ == '__main__': defaultdict_examples()
Output
#3) OrderedDict
This is a subclass of the built-in dict, and it maintains the order of insertion of its items. The general purpose of built-in dict is unordered. Meaning, when iterated over, it returns its items in an arbitrary order, unlike OrderedDict that returns its item in the order in which they were inserted.
OrderedDict is commonly used whenever we want to keep the order in which the items are inserted into our dictionary.
OrderedDict’s methods and description:
Method | Description |
---|---|
o.popitem(last=True) | Returns and removes a key-value pair in LIFO order if last is true or FIFO order if false. |
o.move_to_end(key, last=True) | Moves the existing key to the right end of the ordered dictionary if last is true(the default) or to the left(start) if last is false. If key doesn't exist, the KeyError exception is raised. |
Example: In this example, we shall explore the OrderedDict object and its various methods.
# Import defaultdict from the collections module from collections import OrderedDict def ordereddict_examples(): # Create an empty ordered dict ordered_dict = OrderedDict() # add element one at a time. ordered_dict['red'] = 4 ordered_dict['blue'] = 9 ordered_dict['green'] = 1 print(ordered_dict) # add elements to dict ordered_dict['yellow'] = 11 print(ordered_dict) # remove and add same element with different value del ordered_dict['red'] print(ordered_dict) ordered_dict['red'] = 5 print(ordered_dict) # move the item 'blue' to the end of the dict ordered_dict.move_to_end('blue') print(ordered_dict) # move the item 'red' to the beginning of the dict ordered_dict.move_to_end('red', last=False) print(ordered_dict) # Remove and return the last element in the dict ordered_dict.popitem() # default to True print(ordered_dict) # Remove and return the first element in the dict ordered_dict.popitem(False) print(ordered_dict) if __name__ == '__main__': ordereddict_examples()
Output
#4) ChainMap
It is used to combine several dictionaries that can be searched as one. A search is done from left to right and the first occurrence of the searched key’s value is returned.
Getting keys and values from ChainMap uses both keys() and values() just like the built-in dict. If there are any key duplicates in the ChainMap, then keys() will return just the unique keys while values() will return the value associated with the first occurrence of each key from left to right.
NB: Using ChainMap spares us from using a lot of conditional statements to check if a key is present in each of the dictionaries.
Example: Create a lookup dictionary similar to the basic rule of variable lookup in Python.
The rule of variable lookup in Python is such that a lookup is first done locally(locals()), then globally(globals()), then lastly in the builtins(builtins).
In this example, we shall use ChainMap to create a dictionary where lookup will follow the order.
- User input
- Environment
- Default or local.
Let’s open an editor, paste the below code and name it as chainmap_ex.py
import os, argparse from collections import ChainMap def chainmap_example(): # define default values defaults = {'user': 'guest', 'status': 'visitor'} # Get environment values env = os.environ # Set command-line arguments parser = argparse.ArgumentParser() parser.add_argument('-u', '--user') parser.add_argument('-s', '--status') # Get command-line argument values args_namespace = parser.parse_args() # only retain arguments provided by the user. args_dict = {k: v for k,v in vars(args_namespace).items() if v is not None} # Create our chain dictionary holding user input, environment, and default in that order. args_chain = ChainMap(args_dict, env, defaults) # print values print("User: ",args_chain['user']) print("Status: ", args_chain['status']) if __name__ == '__main__': # set our environment os.environ['user'] = 'Admin' os.environ['status'] = 'Owner' chainmap_example()
Let’s run the code above. Open a terminal in the directory containing this file and run the below command.
python chainmap_ex.py -u 'kevin'
Output
In the command, we passed in the value ‘kevin’ for the User parameter, but didn’t provide any value for Status. However, from the output, we see that indeed the User got the value ‘kevin’ but Status got his value from the environment.
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.
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
Add New Key-Value Pairs
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
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
Python Nested 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
Frequently Asked Questions
Q #1) How do you handle missing keys in Python dictionaries?
Answer: We can handle missing keys in Python dictionaries in the following ways.
For the built-in dict, we can use:
- The get(key, default) method which returns default if the key is missing in the dict.
- setdefault(key, default) which returns default if a key is missing in the dict. Also, it adds the missing key to the dictionary with its default value.
We can also use some mapping types from the collections module like:
- defaultdict(default_factory) which creates items on demand whenever a missing key is accessed.
Q #2) What is the Collections module in Python?
Answer: Collections is a Python built-in module that contains specialized data types that provide alternatives to Python’s built-in general-purpose data types like dict, set, tuple and list.
The commonly used mapping types contained in the Collections module that provide alternatives to the built-in dict are: defaultdict, orderedDict, Counter, and ChainMap.
Q #3) How do you add a new dictionary to an existing ChainMap?
Answer: The ChainMap has the new_child() method that is used to create a new ChainMap object with the new dictionary added to it.
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.
We also summarized the commonly used mapping types implemented in the Collection module.
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