Python Dictionary 8

Add an element to a Nested Dictionary

Example : How to change or add elements in a nested dictionary?

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

employee[3] = {}

employee[3][‘name’] = ‘Neha’
employee[3][‘age’] = ’24’
employee[3][‘sex’] = ‘Female’
employee[3][‘married’] = ‘No’

When we run above program, it will output:

{‘name’: ‘Neha’, ‘age’: ’24’, ‘sex’: ‘Female’, ‘married’: ‘No’}

In the above program, we create an empty dictionary 3 inside the dictionary people.

Then, we add the key:value pair i.e people[3][‘Name’] = ‘Neha’ inside the dictionary 3. Similarly, we do this for key age, sex and married one by one. When we print the people[3], we get key:value pairs of dictionary 3.

#employee details
employee = {1: {'name': 'Amit', 'age': '27', 'sex': 'Male'},
          2: {'name': 'Soniya', 'age': '22', 'sex': 'Female'}}

employee[3] = {}

employee[3]['name'] = 'Neha'
employee[3]['age'] = '24'
employee[3]['sex'] = 'Female'
employee[3]['married'] = 'No'



{'name': 'Neha', 'age': '24', 'sex': 'Female', 'married': 'No'}

Visitor Counter