
Hello Techies,
In this blog, we are learning about Nested Dictionary in Python. Especially, I am covering more topics like create a nested dictionary, how to access elements in the nested dictionary, how to modify them, and so on with the help of examples.
A dictionary in Python is an unordered collection of items in which elements are stored in curly brackets in key-value pairs. To learn more about the dictionary, visit my previous blog based on the dictionary.
Below are the points that we are covering in this blog:
- Python Nested Dictionary(Introduction)
- Create Nested Dictionary in Python
- Access elements of a Nested Dictionary
- Add the element to a Nested Dictionary
- Delete elements from a Nested Dictionary
- Loop through a Nested Dictionary in Python
- Python Merge Nested Dictionaries
- Extract values from Nested Dictionary Python
Table of Contents
#1. Python Nested Dictionary(Introduction)
- Nested Dictionary is to add a dictionary to another dictionary.
- Like dictionaries, it has keys and values.
- Nested Dictionary is an unordered collection of dictionaries.
Example: data = {‘dict1’: {‘key1′:’value1’}, ‘dict2’: {‘key2′:’value2’}}
#2. Create Nested Dictionary in Python
We are creating a nested dictionary to store ID wise course information.
Example:
course = {1: {'name': 'Python', 'fees': '20000'},
2: {'name': 'PHP', 'fees': '15000'}}
print(course)
The output is:
{1: {'name': 'Python', 'fees': '20000'}, 2: {'name': 'PHP', 'fees': '15000'}}
#2. Access elements of a Nested Dictionary
We use indexing [ ] to access elements in a nested dictionary in Python. Let’s look at an example.
Example:
course = {1: {'name': 'Python', 'fees': '20000'},
2: {'name': 'PHP', 'fees': '15000'}}
print(course[2]['name'])
print(course[2]['fees'])
The output is:
PHP
15000
An exception will be raised if you refer to a key that is not in the nested dictionary.
Example:
course = {1: {'name': 'Python', 'fees': '20000'},
2: {'name': 'PHP', 'fees': '15000'}}
print(course[2]['batch'])
The output is:
Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'batch'
You can use the get() method of the dictionary to ignore such errors. If there is a key in the dictionary, this method returns the value, otherwise None, so this method never raises the KeyError.
Example:
course = {1: {'name': 'Python', 'fees': '20000'},
2: {'name': 'PHP', 'fees': '15000'}}
print(course[2].get('batch'))
The output is:
None
#4. Add the element to a Nested Dictionary
Now we will add new information inside the course dictionary, let’s add dictionary 3 with other course details.
Example:
course = {1: {'name': 'Python', 'fees': '20000'},
2: {'name': 'PHP', 'fees': '15000'}}
course[3] = {'name': 'Java', 'fees': '25000'}
print(course)
The output is:
{1: {'name': 'Python', 'fees': '20000'}, 2: {'name': 'PHP', 'fees': '15000'}, 3: {'name': 'Java', 'fees': '25000'}}
This way we can add the dictionary to another dictionary.
#5. Delete elements from a Nested Dictionary
You can delete elements from a nested dictionary using a del statement. Let’s check out an example so you can get an idea of it.
Example:
course = {1: {'name': 'Python', 'fees': '20000'},
2: {'name': 'PHP', 'fees': '15000', 'batch': 3},
3: {'name': 'Java', 'fees': '25000', 'batch': 4}}
del course[3]['batch']
del course[2]
print(course)
The output is:
{1: {'name': 'Python', 'fees': '20000'}, 3: {'name': 'Java', 'fees': '25000'}}
#6. Loop through a Nested Dictionary in Python
Using loops, we can iterate through each element of the nested dictionary.
In this example, we will check How to iterate through a Nested dictionary?
course = {1: {'name': 'Python', 'fees': '20000'},
2: {'name': 'PHP', 'fees': '15000'}}
for key, value in course.items():
print("\ncourse ID:", key)
for val_key in value:
print(val_key + ':', value[val_key])
The output is:
course ID: 1 name: Python fees: 20000
course ID: 2 name: PHP fees: 15000
#7. Python Merge Nested Dictionaries
Update Nested Dictionary Python
The update() function accepts the dictionary and adds the dictionary with the key in it.
Example:
course = {1: {'name': 'Python', 'fees': '20000'},
2: {'name': 'PHP', 'fees': '15000'}}
other_info = {'batch_name':'Python warrior', 'year':2020}
course [2].update(other_info)
print(course)
course = {1: {'name': 'Python', 'fees': '20000'},
2: {'name': 'PHP', 'fees': '15000'}}
java_dict = {3: {'name': 'Java', 'fees': '25000'}}
course.update(java_dict)
print(course)
The output is:
{1: {'name': 'Python', 'fees': '20000'}, 2: {'name': 'PHP', 'fees': '15000', 'batch_name': 'Python warrior', 'year': 2020}}
{1: {'name': 'Python', 'fees': '20000'}, 2: {'name': 'PHP', 'fees': '15000'}, 3: {'name': 'Java', 'fees': '25000'}}
#8. Extract values from Nested Dictionary Python
Sometimes when working with Python dictionaries you may encounter a problem in which you need to extract the selected key values.
Let’s check one example
def find_key_val(key, dictionary):
for k, v in dictionary.items():
if k in key:
yield (k, v)
elif isinstance(v, dict):
for result in find_key_val(key, v):
yield result
elif isinstance(v, list):
for d in v:
for result in find_key_val(key, d):
yield result
my_dict = {'a': {'b': {'c': 8}}, 'd': {'f': 14}, 'h': 50}
keys_list = ['c','h']
list(find_key_val(keys_list, my_dict))
The Output is:
[('c', 8), ('h', 50)]
I hope you understand what I explained in this blog. If you still have any doubts about Nested Dictionary in Python please comment below.
