Delete elements from a Nested Dictionary
In Python, we use “del” statement to delete elements from nested dictionary.
Example : How to delete elements from a nested dictionary?
employee = {1: {‘name’: ‘Amit’, ‘age’: ’27’, ‘sex’: ‘Male’},
2: {‘name’: ‘Soniya’, ‘age’: ’22’, ‘sex’: ‘Female’},
3: {‘name’: ‘Neha’, ‘age’: ’24’, ‘sex’: ‘Female’, ‘married’: ‘No’},
4: {‘name’: ‘Sumit’, ‘age’: ’29’, ‘sex’: ‘Male’, ‘married’: ‘Yes’}}
del employee[3][‘married’]
del employee[4][‘married’]
print(employee[3])
print(employee[4])
When we run above program, it will output:
{‘name’: ‘Neha’, ‘age’: ’24’, ‘sex’: ‘Female’}
{‘name’: ‘Sumit’, ‘age’: ’29’, ‘sex’: ‘Male’}
In the above program, we delete the key:value pairs of married from internal dictionary 3 and 4. Then, we print the employee[3] and employee[4] to confirm changes.
#employee details employee = {1: {'name': 'Amit', 'age': '27', 'sex': 'Male'}, 2: {'name': 'Soniya', 'age': '22', 'sex': 'Female'}, 3: {'name': 'Neha', 'age': '24', 'sex': 'Female', 'married': 'No'}, 4: {'name': 'Sumit', 'age': '29', 'sex': 'Male', 'married': 'Yes'}} del employee[3]['married'] del employee[4]['married'] print(employee[3]) print(employee[4])
Output:
{'name': 'Neha', 'age': '24', 'sex': 'Female'} {'name': 'Sumit', 'age': '29', 'sex': 'Male'} >>>
Example : How to delete dictionary from a nested dictionary?
employee = {1: {‘name’: ‘Amit’, ‘age’: ’27’, ‘sex’: ‘Male’},
2: {‘name’: ‘Soniya’, ‘age’: ’22’, ‘sex’: ‘Female’},
3: {‘name’: ‘Neha’, ‘age’: ’24’, ‘sex’: ‘Female’},
4: {‘name’: ‘Sumit’, ‘age’: ’29’, ‘sex’: ‘Male’}}
del employee[3], employee[4]
print(people)
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, we delete both the internal dictionary 3 and 4 using delfrom the nested dictionary employee. Then, we print the nested dictionary employee to confirm changes.
#employee details employee = {1: {'name': 'Amit', 'age': '27', 'sex': 'Male'}, 2: {'name': 'Soniya', 'age': '22', 'sex': 'Female'}, 3: {'name': 'Neha', 'age': '24', 'sex': 'Female'}, 4: {'name': 'Sumit', 'age': '29', 'sex': 'Male'}} del employee[3], employee[4] print(employee)
Output:
{1: {'name': 'Amit', 'age': '27', 'sex': 'Male'}, 2: {'name': 'Soniya', 'age': '22', 'sex': 'Female'}} >>>