nested_dict = {
'dict1': {'key1': 'value1'},
'dict2': {'key2': 'value2'}
}
In this example, nested_dict
contains two dictionaries: dict1
and dict2
. Each inner dictionary stores its own key-value pairs.employee = {
'name': 'John',
'age': 37,
'job': 'Software Developer',
'city': 'Bangalore',
'email': 'john@gmail.com'
}
Handling hundreds of employees calls for nested dictionaries:employees = {
101: {
'name': 'John',
'age': 37,
'job': 'Software Developer'
},
102: {
'name': 'Jane',
'age': 29,
'job': 'Data Analyst'
}
}
nested_dict = {
'dict1': {'Color': 'Red', 'Shape': 'Square'},
'dict2': {'Color': 'Pink', 'Shape': 'Round'}
}
print(nested_dict)
Output:{'dict1': {'Color': 'Red', 'Shape': 'Square'}, 'dict2': {'Color': 'Pink', 'Shape': 'Round'}}
nested_dict['dict3'] = {}
nested_dict['dict3']['Color'] = 'Blue'
nested_dict['dict3']['Shape'] = 'Rectangle'
print(nested_dict)
Output:{
'dict1': {'Color': 'Red', 'Shape': 'Square'},
'dict2': {'Color': 'Pink', 'Shape': 'Round'},
'dict3': {'Color': 'Blue', 'Shape': 'Rectangle'}
}
nested_dict['dict4'] = {'Color': 'Green', 'Shape': 'Triangle'}
nested_dict = {
'dict1': {'Color': 'Red', 'Shape': 'Square'},
'dict2': {'Color': 'Pink', 'Shape': 'Round'}
}
print(nested_dict['dict1']['Color']) # Output: Red
print(nested_dict['dict2']['Shape']) # Output: Round
nested_dict['dict1']['Color'] = 'Yellow'
print(nested_dict['dict1']['Color']) # Output: Yellow
del
keyword to remove a key-value pair:del nested_dict['dict1']['Color']
print(nested_dict)
Output:{'dict1': {'Shape': 'Square'}, 'dict2': {'Color': 'Pink', 'Shape': 'Round'}}
del nested_dict['dict1']
print(nested_dict)
Output:{'dict2': {'Color': 'Pink', 'Shape': 'Round'}}
.get()
or collections.defaultdict
.