Python | Add keys to nested dictionary
Addition of keys in dictionaries have been discussed many times, but sometimes, we might have a problem in which we require to alter/add keys in the nested dictionary. This type of problem is common in today’s world with advent of NoSQL databases. Let’s discuss certain ways in which this problem can be solved.
Method #1: Using for loop
Step-by-step approach:
- Create a function named add_keys_nested_dict that takes in two arguments d and keys.
- Loop through each key in keys.
- Check if the key exists in the dictionary d. If it does not exist, create a new nested dictionary.
- Update the dictionary d with the new nested dictionary.
- Set the default value of the last key to 1.
- Call the function add_keys_nested_dict with the test dictionary and keys list.
- Print the updated dictionary.
Python3
def add_keys_nested_dict(d, keys):
for key in keys:
if key not in d:
d[key] = {}
d = d[key]
d.setdefault(keys[ - 1 ], 1 )
test_dict = { 'GFG' : { 'rate' : 4 , 'since' : 2012 }}
print ( "The original dictionary is: " + str (test_dict))
add_keys_nested_dict(test_dict, [ 'GFG' , 'rank' ])
print ( "Dictionary after nested key update: " + str (test_dict))
|
Output
The original dictionary is: {'GFG': {'rate': 4, 'since': 2012}}
Dictionary after nested key update: {'GFG': {'rate': 4, 'since': 2012, 'rank': {'rank': 1}}}
Time complexity: O(n), where n is the number of keys.
Auxiliary space: O(1), since we are not using any additional data structure.
Method #2: Using dictionary brackets This task can be easily performed using the naive method of just keep nesting the dictionary brackets with the new value and new key is created on the go and the dictionary is updated.
Python3
test_dict = { 'GFG' : { 'rate' : 4 , 'since' : 2012 }}
print ("The original dictionary is : " + str (test_dict))
test_dict[ 'GFG' ][ 'rank' ] = 1
print ("Dictionary after nested key update : " + str (test_dict))
|
Output :
The original dictionary is : {'GFG': {'rate': 4, 'since': 2012}}
Dictionary after nested key update : {'GFG': {'rate': 4, 'since': 2012, 'rank': 1}}
Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(n), to store the keys and values in dictionary.
Method #3: Using update() This method is used in cases where more than one keys need to be added to the nested dictionaries. The update function accepts the dictionary and added the dictionary with the keys in it.
Python3
test_dict = { 'GFG' : { 'rate' : 4 , 'since' : 2012 }}
upd_dict = { 'rank' : 1 , 'popularity' : 5 }
print ("The original dictionary is : " + str (test_dict))
test_dict[ 'GFG' ].update(upd_dict)
print ("Dictionary after nested key update : " + str (test_dict))
|
Output :
The original dictionary is : {'GFG': {'rate': 4, 'since': 2012}}
Dictionary after nested key update : {'GFG': {'popularity': 5, 'rate': 4, 'since': 2012, 'rank': 1}}
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #4: Using setdefault()
This approach uses dict.setdefault() method to add keys to the nested dictionary. The setdefault() is a pre-defined function in Python and is used to set a value in the dictionary, if the key is not present. If the key is present, it will not change the current value of the key. This method returns the value of the key. In this code, we are setting the key ‘rank’ to the value 1 in the nested dictionary test_dict.
Python3
test_dict = { 'GFG' : { 'rate' : 4 , 'since' : 2012 }}
print ( "The original dictionary is : " + str (test_dict))
test_dict.setdefault( 'GFG' , {}).setdefault( 'rank' , 1 )
print ( "Dictionary after nested key update : " + str (test_dict))
|
Output
The original dictionary is : {'GFG': {'rate': 4, 'since': 2012}}
Dictionary after nested key update : {'GFG': {'rate': 4, 'since': 2012, 'rank': 1}}
Time Complexity: O(1)
Auxiliary Space: O(1)
Method #5: Using Recursion
Base Case: If list of keys is empty. return the dictionary.
Else : pop the first key from the list and use it to access the corresponding value in the dictionary.
Recursively call the function with the value as the new dictionary and the remaining keys as the new list of keys.
Python3
def add_keys_nested_dict(d, keys):
if len (keys) = = 1 :
d.setdefault(keys[ 0 ], 1 )
else :
key = keys[ 0 ]
if key not in d:
d[key] = {}
add_keys_nested_dict(d[key], keys[ 1 :])
test_dict = { 'GFG' : { 'rate' : 4 , 'since' : 2012 }}
print ( "The original dictionary is : " + str (test_dict))
add_keys_nested_dict(test_dict, [ 'GFG' , 'rank' ])
print ( "Dictionary after nested key update : " + str (test_dict))
|
Output
The original dictionary is : {'GFG': {'rate': 4, 'since': 2012}}
Dictionary after nested key update : {'GFG': {'rate': 4, 'since': 2012, 'rank': 1}}
Time Complexity: O(N), where n is the number of keys in the list.
Auxiliary Space: O(N), as we are creating a new dictionary.
Last Updated :
15 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...