In Python, a Dictionary can be seen as a collection of key-value pairs. A dictionary can contain dictionaries, this is called nested dictionaries. We are going to learn how to parse a nested dictionary in Python.
This guide will provide you with the clues to parse such structures by using Python core modules and manipulating statements.
What is a Nested Dictionary?
A nested dictionary is a dictionary that contains other dictionaries, which in turn can contain dictionaries themselves, and so on to arbitrary depth. This is known as “nesting”.
Example of Nested Dictionary
Let’s define a simple nested dictionary in Python:
nested_dictionary = { 'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2', 'key_3': 'value_3', 'key_4': 'value_4'}, 'dictC': {'key_5': 'value_5'} }
How to Parse a Nested Dictionary
To parse the nested dictionary, we can use Python basic “for” loop or “dictionary comprehension” method.
Using for loop
Parsing the nested dictionary using for loops:
for dict_key, dict_value in nested_dictionary.items(): print('Dictionary', dict_key) for key in dict_value: print(key, '->', dict_value[key])
The .items() method of the dictionary object returns a list of dictionary entries, which are tuples containing the pair of keys and values. Thus, you can parse the individual items of the nested dictionaries.
Output:
Dictionary dictA key_1 -> value_1 Dictionary dictB key_2 -> value_2 key_3 -> value_3 key_4 -> value_4 Dictionary dictC key_5 -> value_5
Using Dictionary comprehension
Accessing a specific key-value of the nested dictionary using dictionary comprehension.
{name: nested_dictionary[name]['key_1'] for name in nested_dictionary if 'key_1' in nested_dictionary[name]}
Full Code
nested_dictionary = { 'dictA': {'key_1': 'value_1'}, 'dictB': {'key_2': 'value_2', 'key_3': 'value_3', 'key_4': 'value_4'}, 'dictC': {'key_5': 'value_5'} } for dict_key, dict_value in nested_dictionary.items(): print('Dictionary', dict_key) for key in dict_value: print(key, '->', dict_value[key]) result = {name: nested_dictionary[name]['key_1'] for name in nested_dictionary if 'key_1' in nested_dictionary[name]} print() print(result)
Conclusion
Python provides various control structures and methods that are extremely useful when working with different types of data structures. Here we saw how to access, parse, and work with a nested dictionary.
The important concept is that you can access key-value pairs of inner dictionaries by using the keys of outer dictionaries. In summary, always keep practicing and experimenting with examples and exercises appearing in various Python tutorials and you will get the hang of it.