How to Create a Nested Dictionary in Python
A Python nested dictionary is a dictionary within another dictionary. This lets you store data using the key-value mapping structure within an existing dictionary.
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Get exclusive scholarships and prep courses
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Get exclusive scholarships and prep courses
When you're working with dictionaries in Python, you may encounter a situation where a dictionary contains another dictionary.
This structure of data is often referred to as a nested dictionary, and has a wide range of potential use cases in Python code.
This tutorial will discuss the basics of Python nested dictionaries. We'll walk through a few examples so you can learn how to create and modify a nested dictionary.
Python Dictionary Refresher
The dictionary is Python's mapping data type. A Python dictionary binds—or map—keys to values, and provide an effective way of storing data.
When a key is mapped to a value, you can retrieve the data stored in that value by referencing the key. So, in a sense, the key acts like a label. Here's an example of a dictionary which stores the prices of ice cream flavors sold at a local ice cream store, The Frozen Spoon:
ice_cream_flavors = { "Vanilla": 0.50, "Chocolate": 0.50, "Cookies and Cream": 0.75, "Strawberry": 0.65, "Buttered Pecan": 0.90 }
The keys in this dictionary are the names of our ice creams (i.e. "Vanilla"), and the values are the prices per scoop of each ice cream.
Python Nested Dictionary
Python nested dictionaries are dictionaries inside a dictionary. They are used to represent dictionary data within another dictionary. You can nest as many dictionaries in a dictionary as you want.
81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today.
The average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job.
Nested dictionaries are useful if you want to store a range of component dictionaries in one big dictionary.
Let's walk through an example to illustrate how nested dictionaries work. Suppose we want to create a dictionary which stores dictionaries about each flavor of ice cream sold at The Frozen Spoon. Each dictionary in our big dictionary should list:
- The name of the ice cream
- Its price
- How many pints are in stock
Here is what a nested dictionary that stores this data would look like:
ice_cream_flavors = { 0: { "flavor": "Vanilla", "price": 0.50, "pints": 20 }, 1: { "flavor": "Chocolate", "price": 0.50, "pints": 31 }, 2: { "flavor": "Cookies and Cream", "price": 0.75, "pints": 14 } }
In our code, we have declared one big dictionary called ice_cream_flavors. This dictionary contains three dictionaries, each of which stores information on a particular flavor of ice cream.
If we did not use a nested dictionary, we would have had to store each of these dictionaries in separate variables. This is counterintuitive because each dictionary stores information about ice cream flavors.
Access Items in a Nested Dictionary
To access an item in a nested dictionary, we can use the indexing syntax.
Suppose we want to retrieve the price of the ice cream with the index value 0 in our dictionary. We could do so using this code:
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Get exclusive scholarships and prep courses
ice_cream_flavors = { 0: { "flavor": "Vanilla", "price": 0.50, "pints": 20 }, 1: { "flavor": "Chocolate", "price": 0.50, "pints": 31 }, 2: { "flavor": "Cookies and Cream", "price": 0.75, "pints": 14 } } print(ice_cream_flavors[0]["price"]) print(ice_cream_flavors[0]["flavor"])
Our code returns:
In this code, we first specify the item key whose value is in our big dictionary that we want to retrieve. In this case, we wanted to access the record with the index value 0.
Then, we specify the name of the item in our inner dictionary that we want to retrieve. In this case, we wanted to retrieve the price of our ice cream and the flavor. So, we specified price and flavor in both our print() statements.
Nested Dictionary Python: Add Element
To add an element to a nested dictionary, we can use the same syntax we used to modify an item. There is no method you should use to add an item to a nested dictionary. You need to use the assignment operator.
The syntax for adding an item is as follows:
dictionary_name[new_key_name] = new_value
Suppose we have a dictionary that stores information on a vanilla ice cream for sale. We want to track whether there is a discount on the ice cream. We could do this using the following code:
ice_cream_flavors = { 0: { "flavor": "Vanilla", "price": 0.50, "pints": 20 }, 1: { "flavor": "Chocolate", "price": 0.50, "pints": 31 }, 2: { "flavor": "Cookies and Cream", "price": 0.75, "pints": 14 } } ice_cream_flavors[0]["discount"] = True print(ice_cream_flavors[0])
Let's run our code and see what happens:
{'flavor': 'Vanilla', 'price': 0.5, 'pints': 20, 'discount': True}
Our dictionary is stored in the Python variable "ice_cream_flavors".
We added a key called discount to the dictionary. The index position of this key is 0. We set the value of this key to True. Then, we printed out the dictionary with the index value 0 in our ice_cream_flavors nested dictionary. This shows that our discount key has been added.
We can use this syntax to update an element in an existing dictionary. Suppose we wanted to change the price of our chocolate ice cream to be $0.45 per scoop. We could do so using this code:
ice_cream_flavors = { 0: { "flavor": "Vanilla", "price": 0.50, "pints": 20 }, 1: { "flavor": "Chocolate", "price": 0.50, "pints": 31 }, 2: { "flavor": "Cookies and Cream", "price": 0.75, "pints": 14 } } ice_cream_flavors[1]["price"] = 0.45 print(ice_cream_flavors[1])
Our code returns:
"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
{'flavor': 'Chocolate', 'price': 0.45, 'pints': 31}
We changed the value of the price key for our chocolate ice cream to be $0.45.
To do so, we specified the index value of the dictionary whose price value we wanted to change as 1. This value contains the information about chocolate ice creams in our dictionary. Then, we assigned a new value to the price key.
Nested Dictionary Python: Delete Element
To delete an item stored in a nested dictionary, we can use the del statement. The del statement lets you delete an object. del is written like a Python break statement, on its own line, followed by the item in the dictionary that you want to delete.
Suppose we are no longer offering cookies and cream ice cream at our store temporarily. Our freezer that stored the cookies and cream ice cream stopped working and the goods melted.
We could remove this ice cream from our nested dictionary using the following code:
ice_cream_flavors = { 0: { "flavor": "Vanilla", "price": 0.50, "pints": 20 }, 1: { "flavor": "Chocolate", "price": 0.50, "pints": 31 }, 2: { "flavor": "Cookies and Cream", "price": 0.75, "pints": 14 } } del ice_cream_flavors[2] print(ice_cream_flavors)
Our code returns:
{0: {'flavor': 'Vanilla', 'price': 0.5, 'pints': 20}, 1: {'flavor': 'Chocolate', 'price': 0.5, 'pints': 31}}
In our code, we used a del statement to delete the value in our nested dictionary whose key was equal to 2. As you can see, this removed the entry for Cookies and Cream from our nested dictionary.
Iterate Through a Python Nested Dictionary
Now, suppose we want to print out the contents of each dictionary in our nested dictionary to the console. How can we accomplish this task?
That's a great question. To print out the contents of our nested dictionary, we can iterate through it using a Python for loop. We are also going to use the Python dictionary items() method to retrieve a list of the keys and values in our dictionary:
ice_cream_flavors = { 0: { "flavor": "Vanilla", "price": 0.50, "pints": 20 }, 1: { "flavor": "Chocolate", "price": 0.50, "pints": 31 }, 2: { "flavor": "Cookies and Cream", "price": 0.75, "pints": 14 } } for key, value in ice_cream_flavors.items(): print("Ice Cream:", key) for k, v in value.items(): print(k + ":", value[k])
Our code returns:
Ice Cream: 0 flavor: Vanilla price: 0.5 pints: 20 Ice Cream: 1 flavor: Chocolate price: 0.5 pints: 31 Ice Cream: 2 flavor: Cookies and Cream price: 0.75 pints: 14
Let's break down our code. First, we have defined our nested dictionary of ice cream flavors.
Then, we have defined a for loop that goes through each key and value in the ice_cream_flavors dictionary. This loop uses .items() to generate a list of all the keys and values in our ice_cream_flavors dictionary, over which the loop can iterate.
Then, we print Ice Cream: followed by the key associated with a particular ice cream.
Next, we use another for loop to loop through every item in each value in our nested dictionary. This refers to each inner entry in our nested dictionary (such as the ones for vanilla and chocolate). This loop prints out the name of each key in our inner dictionaries, followed by a colon, then the value associated with that key.
Conclusion
Nested dictionaries allow you to store dictionaries inside a dictionary in Python.
This tutorial discussed, with reference to examples, how to:
- Create a nested dictionary
- Add elements to and update elements in a nested dictionary
- Remove elements from a nested dictionary
- Iterate through a nested dictionary
To learn more about coding in Python, read our How to Code in Python guide.
How to Create a Nested Dictionary in Python
Source: https://careerkarma.com/blog/python-nested-dictionary/