Python Dictionary 6

Python Nested Dictionary

In Python, a dictionary is an unordered collection of items.
For example:
dictionary = {‘key_1′:’value_1′,’key_2′:’value_2’}

Here, dictionary has a key:value pair enclosed within curly brackets {}.

What is Nested Dictionary in Python?

In Python, a nested dictionary is a dictionary inside a dictionary. It’s a collection of dictionaries into one single dictionary.

nested_dict = { ‘dictA’: {‘key_1’: ‘value_1’},
‘dictB’: {‘key_2’: ‘value_2’}}

Here, the nested_dict is a nested dictionary with the dictionary dictA and dictB. They are two dictionary each having own key and value.

Create a Nested Dictionary

We’re going to create dictionary of people within a dictionary.

Example : How to create a nested dictionary

employee = {1: {‘name’: ‘Amit’, ‘age’: ’27’, ‘sex’: ‘Male’},
2: {‘name’: ‘Soniya’, ‘age’: ’22’, ‘sex’: ‘Female’}}
print(employee)

When we run above program, it will output:

{1: {‘name’: ‘Amit’, ‘age’: ’27’, ‘sex’: ‘Male’}, 2: {‘name’: ‘Soniya’, ‘age’: ’22’, ‘sex’: ‘Female’}}

In the above program, employee is a nested dictionary. The internal dictionary 1 and 2 is assigned to employee. Here, both the dictionary have key name, age , sex with different values. Now, we print the result of employee.

#employee details

employee = {1: {'name': 'Amit', 'age': '27', 'sex': 'Male'},
          2: {'name': 'Soniya', 'age': '22', 'sex': 'Female'}}
print(employee)

Output:

{1: {'name': 'Amit', 'age': '27', 'sex': 'Male'}, 2: {'name': 'Soniya', 'age': '22', 'sex': 'Female'}}
>>>