Open In App

Add Keys to Nested Dictionary

Last Updated : 30 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of adding keys to a nested dictionary in Python involves inserting new keys or updating the values of existing ones within the nested structure. Since Python dictionaries do not allow duplicate keys, if a key already exists then its value will be updated. If the key doesn’t exist at any level, it will be added. Consider a dictionary d = {‘GFG’: {‘rate’: 4, ‘since’: 2012}}. If we want to add a new key ‘rank’ under the ‘GFG’ dictionary with a value of 1. After this operation, the dictionary d will be updated to {‘GFG’: {‘rate’: 4, ‘since’: 2012, ‘rank’: 1}}.

Using defaultdict

defaultdict that automatically creates missing keys with a default value such as an empty dictionary when accessed. This is useful when we need to add keys to nested dictionaries without manually checking for the existence of each key at each level.

Python
d = {'GFG': {'rate': 4, 'since': 2012}}
k = ['GFG', 'rank'] # 'k' contains the keys 

temp = d

# Loop through all the keys in 'k'
for key in k[:-1]:
    temp = temp.setdefault(key, {})

temp.setdefault(k[-1], 1)
print(d)

Output
{'GFG': {'rate': 4, 'since': 2012, 'rank': 1}}

Explanation:

  • temp is initially set to reference the dictionary d .
  • k[:-1] gives [‘GFG’] which is all keys in k except the last one.
  • After the loop, temp points to the dictionary {‘rate’: 4, ‘since’: 2012}.
  • temp.setdefault(k[-1], 1) checks if ‘rank’ exists in temp. If not, it adds ‘rank’ with a default value of 1.

Using reduce()

reduce() applies a function sequentially to the keys in a list, ensuring each key is added to the dictionary in order.

Python
from functools import reduce

d = {'GFG': {'rate': 4, 'since': 2012}}
k = ['GFG', 'rank']  # 'k' contains the keys 

reduce(lambda d, key: d.setdefault(key, {}), k[:-1], a).setdefault(k[-1], 1)

print(a)

Output
{'GFG': {'rate': 4, 'since': 2012, 'rank': 1}}

Explanation:

  • reduce() applies a function sequentially to the items in the iterable k[:-1] all keys except the last one and processing each item one by one.
  • lambda d, key: d.setdefault(key, {}) checks if the key exists in the dictionary d. If the key is already present then it returns the corresponding value but if the key is not found, it adds the key with an empty dictionary {} as its value.
  • .setdefault(k[-1], 1) checks if the key ‘rank’ exists in the dictionary. If it doesn’t, it sets ‘rank’ to 1 and returns 1 otherwise it returns the existing value of ‘rank’.

Using update()

update() directly add or update key-value pairs in a dictionary. When dealing with nested dictionaries, we can use it to insert or modify values at any depth, which is particularly useful when the exact path and values are already known.

Python
d1 = {'GFG': {'rate': 4, 'since': 2012}}
d2 = {'rank': 1, 'popularity': 5}

# Manually updating nested dictionary
d1['GFG']['rank'] = d2['rank']
d1['GFG']['popularity'] = d2['popularity']

print(str(d1))

Output
{'GFG': {'rate': 4, 'since': 2012, 'rank': 1, 'popularity': 5}}

Explanation:

  • d[‘GFG’][‘rank’] = upd_d[‘rank’] adds the ‘rank’ key under ‘GFG’ with the value 1.
  • d[‘GFG’][‘popularity’] = upd_d[‘popularity’] adds the ‘popularity’ key with the value 5.

Using loop

Loop approach involves manually iterating over a list of keys and ensuring that each key exists, creating any missing intermediate dictionaries. Once the loop finishes, we can set the final key’s value.

Python
d = {'GFG': {'rate': 4, 'since': 2012}}

k = ['GFG', 'rank'] # `k` contain keys

temp = d  # Set temp as a reference to dictionary `d`

# Iterate through the keys in `k`
for i in k:
    if i not in temp:
        temp[i] = {}
    temp = temp[i]
temp.setdefault(k[-1], 1)

print(str(d))

Output
{'GFG': {'rate': 4, 'since': 2012, 'rank': {'rank': 1}}}

Explanation:

  • If a key doesn’t exist in temp, an empty dictionary is assigned to it.
  • temp = temp[i] updates temp to point to the newly created or existing dictionary for the next iteration.
  • After the loop, temp points to the last nested dictionary.
  • temp.setdefault(k[-1], 1) adds the final key (‘rank’) with the value 1 if it doesn’t exist.


Next Article

Similar Reads