Iterating Through a Nested Dictionary
Using the for loops, we can iterate through each elements in a nested dictionary.
Example : How to iterate through a Nested dictionary?
employee = {1: {‘Name’: ‘Amit’, ‘Age’: ’27’, ‘Sex’: ‘Male’},
2: {‘Name’: ‘Soniya’, ‘Age’: ’22’, ‘Sex’: ‘Female’}}
for p_id, p_info in employee.items():
print(“\nEmployee ID:”, p_id)
for key in p_info:
print(key + ‘:’, p_info[key])
When we run above program, it will output:
Employee ID: 1
Name: John
Age: 27
Sex: Male
Employee ID: 2
Name: Marie
Age: 22
Sex: Female
In the above program, the first loop returns all the keys in the nested dictionary employee. It consists of the IDs p_id of each employee. We use these IDs to unpack the information p_info of each person.
The second loop goes through the information of each person. Then, it returns all of the keys name, age, sex of each employee’s dictionary.
Now, we print the key of the employee’s information and the value for that key.
#employee details
employee = {1: {‘Name’: ‘Amit’, ‘Age’: ’27’, ‘Sex’: ‘Male’},
2: {‘Name’: ‘Soniya’, ‘Age’: ’22’, ‘Sex’: ‘Female’}}
for p_id, p_info in employee.items():
print(“\nEmployee ID:”, p_id)
for key in p_info:
print(key + ‘:’, p_info[key])
#employee details employee = {1: {'Name': 'Amit', 'Age': '27', 'Sex': 'Male'}, 2: {'Name': 'Soniya', 'Age': '22', 'Sex': 'Female'}} for p_id, p_info in employee.items(): print("\nEmployee ID:", p_id) for key in p_info: print(key + ':', p_info[key])
Output:
Employee ID: 1 Name: Amit Age: 27 Sex: Male Employee ID: 2 Name: Soniya Age: 22 Sex: Female >>>