To access a nested dictionary in Python, apply the access operator twice (or more).
For example, let’s access the name of a student data dictionary with the student ID of 123:
students = { 123: {'name' : 'Alice', 'age': '23'}, 321: {'name' : 'Bob', 'age': '34'} } name = students[123]['name'] print(name)
Output:
Alice
This guide teaches you how to access nested dictionaries in Python. Besides, you learn how to create a nested dictionary, access the elements, and modify them. I’ve included a bunch of useful examples and different scenarios you might need to do this.
What Is a Dictionary in Python?
And just in case you are new to dictionaries, a dictionary is an unordered collection of labeled items.
student = {'name' : 'Alice', 'age': '23'}
A traditional “one-dimensional” dictionary has key-value pairs as highlighted above. The key is the label of the value it refers to.
For example, you can get the name and ages of the students in the above dictionary by accessing them with the keys:
name = student["name"] age = student["age"]
Ok, so that’s just a quick recap on how the Python dictionary works and how to access its values.
What Is a Nested Dictionary?
The word “nested” refers to similar objects placed inside one another. Nested dictionaries in Python means placing dictionaries inside dictionaries.
For example, here is a nested students dictionary that consists of data from multiple students associated with a three-digit student ID:
students = { 123: {'name' : 'Alice', 'age': '23'}, 321: {'name' : 'Bob', 'age': '34'} }
Here students is a dictionary of dictionaries where a student ID is a key and the student data dictionary is a value.
How to Access a Nested Dictionary Element?
To access a nested dictionary value in Python, you need to:
- Access the dictionary inside of a dictionary by its key.
- Access the value of the accessed dictionary by the associated key.
Let’s take a look at accessing the values of the nested students dictionary from the previous section.
students = { 123: {'name' : 'Alice', 'age': '23'}, 321: {'name' : 'Bob', 'age': '34'} }
To pick a student from the students dictionary, one needs to know the student ID of the particular student.
Let’s assume I’m Alice trying to access my student data from a student database. I know that my student ID is 123. So, I can access the dictionary with that value:
alice = students[123] print(alice)
Output:
{'name': 'Alice', 'age': '23'}
This successfully shows the dictionary data associated with Alice.
To access a particular value in the data, call the dictionary accessing operator again on the accessed data dictionary.
For example, let’s say I only want to check the name of the student with an ID of 123:
name = students[123]['name'] print(name)
Output:
Alice
As you can see, in the above code, I first access the dictionary data associated with ID 123. Because this value is also dictionary, I can continue accessing its values the same way.
Of course, you can split the process such that you:
- Access the inner dictionary and store it in a variable.
- Access the value of the inner dictionary variable and store it in another variable.
For instance:
student = students[123] name = student["name"] print(name)
Output:
Alice
Access Nested Dictionaries More Safely
Thus far you have seen how to access dictionary values without thinking about what happens if a key doesn’t exist.
Let’s continue exploration with the students dictionary.
students = { 123: {'name' : 'Alice', 'age': '23'}, 321: {'name' : 'Bob', 'age': '34'} }
It’s important to understand that in the previous example you assumed the key exists in a dictionary like this.
But let’s see what happens if this is not the case.
For example, let’s try to find the student data of a student with ID 999:
student = students[999] print(student)
This results in an error that crashes the program.
Traceback (most recent call last): File "<string>", line 6, in <module> KeyError: 999
If someone accidentally enters a wrong value in the dictionary, you don’t want the entire program to crash.
To prevent this, you can use the dictionary.get() method to access values more securely. If a key passed into this function doesn’t exist, the program doesn’t crash.
For example:
student = students.get(999) print(student)
Output:
None
As you can see, the result is None instead of an error. This is much better than crashing the program.
To access a nested dictionary in this more safe way:
- Call the dictionary.get() method on a nested dictionary to access an inner dictionary.
- Use an if-else to make sure the returned dictionary is not None.
- Call the dictionary.get() on the inner dictionary to get a corresponding value.
Here is an example:
student = students.get(999) if student != None: name = student.get('name') print(name) else: print("Value not found")
Output:
Value not found
Because there is no key 999 in the students dictionary, the inner dictionary returned was None. Thus, only the else block was executed.
For reference, let’s make sure this code also works when the key exists.
student = students.get(123) if student != None: name = student.get('name') print(student) else: print("Value not found")
Output:
Alice
As you can see, this is a more secure way to access the nested dictionary values. Whether the values exist or not, the program doesn’t crash with an error.
How to Add a Value to a Nested Dictionary?
To introduce a new value to a nested dictionary, you need to use the dictionary access operator once again.
For instance, let’s add a new hobbies key to one of the student objects in the students dictionary:
students = { 123: {'name' : 'Alice', 'age': '23'}, 321: {'name' : 'Bob', 'age': '34'} } students[123]['hobbies'] = ['Jogging', "Tennis", "Disc Golf"] print(students)
Output:
{123: {'name': 'Alice', 'age': '23', 'hobbies': ['Jogging', 'Tennis', 'Disc Golf']}, 321: {'name': 'Bob', 'age': '34'}}
Notice that this example only works if the key 123 exists. If it doesn’t, the program will crash. So make sure to check the key is in the dictionary before adding a value to it!
students = { 123: {'name' : 'Alice', 'age': '23'}, 321: {'name' : 'Bob', 'age': '34'} } target = 999 if target in students: students[target]['hobbies'] = ['Jogging', "Tennis", "Disc Golf"]
How to Remove a Value from a Nested Dictionary?
Removing a value from a nested dictionary is no different than removing a value from a one-dimensional dictionary. All you need to do is access the value and call the del operator on it.
For example, let’s remove the name of a student with ID 123:
students = { 123: {'name' : 'Alice', 'age': '23'}, 321: {'name' : 'Bob', 'age': '34'} } del students[123]['name'] print(students)
Output:
{123: {'age': '23'}, 321: {'name': 'Bob', 'age': '34'}}
How to Add Another Dictionary to a Nested Dictionary?
To add a new dictionary in a nested dictionary is no different than adding a new value to a regular dictionary. Instead of adding a single value to a key, you add an entire dictionary.
To add a new key-value pair to a dictionary, use the dictionary access operator. Pass the access operator the new key ass an argument and assign a value to it.
For example, let’s add a new student dictionary to the students dictionary:
students = { 123: {'name' : 'Alice', 'age': '23'}, 321: {'name' : 'Bob', 'age': '34'} } students[999] = {'name' : 'Charlie', 'age': '20'} print(students)
Output:
{123: {'name': 'Alice', 'age': '23'}, 321: {'name': 'Bob', 'age': '34'}, 999: {'name': 'Charlie', 'age': '20'}}
Now there are three students in the dictionary.
How to Iterate Through a Nested Dictionary?
Once again, there is nothing complicated going on when iterating a dictionary of dictionaries.
To iterate a dictionary in Python, use the dictionary.items() method to convert the dictionary in an iterable format. Then assign the key and value to temporary variables.
For example, let’s print the names of the student dictionaries:
students = { 123: {'name' : 'Alice', 'age': '23'}, 321: {'name' : 'Bob', 'age': '34'} } for key, value in students.items(): print(f"{key}: {value['name']}")
Output:
123: Alice 321: Bob
Conclusion
Today you learned how to access dictionaries inside of dictionaries. In other words, you learned how to work with nested dictionaries.
To put it short, a nested dictionary is a name used to refer to a dictionary whose values are also dictionaries.
To access these nested dictionaries inside of dictionaries, the same dictionary accessing rules apply.
- First access the inner dictionary with its key.
- Then access the values of the inner dictionary by using the keys it has.
Thanks for reading. Happy coding!