Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Dictionary keys as a list in Python
Next article icon

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.

Table of Content

  • Using reduce()
  • Using update()
  • Using loop

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
Dictionary keys as a list in Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python dictionary-programs
  • Python-nested-dictionary
Practice Tags :
  • python

Similar Reads

  • Python - Add Items to Dictionary
    We are given a dictionary and our task is to add a new key-value pair to it. For example, if we have the dictionary d = {"a": 1, "b": 2} and we add the key "c" with the value 3, the output will be {'a': 1, 'b': 2, 'c': 3}. This can be done using different methods like direct assignment, update(), or
    3 min read
  • Dictionary keys as a list in Python
    In Python, we will encounter some situations where we need to extract the keys from a dictionary as a list. In this article, we will explore various easy and efficient methods to achieve this. Using list() The simplest and most efficient way to convert dictionary keys to lists is by using a built-in
    2 min read
  • Add Same Key in Python Dictionary
    The task of adding the same key in a Python dictionary involves updating the value of an existing key rather than inserting a new key-value pair. Since dictionaries in Python do not allow duplicate keys, adding the same key results in updating the value of that key. For example, consider a dictionar
    3 min read
  • Python Print Dictionary Keys and Values
    When working with dictionaries, it's essential to be able to print their keys and values for better understanding and debugging. In this article, we'll explore different methods to Print Dictionary Keys and Values. Example: Using print() Method [GFGTABS] Python my_dict = {'a': 1, 'b'
    2 min read
  • Add Key to Dictionary Python Without Value
    In Python, dictionaries are a versatile and widely used data structure that allows you to store and organize data in key-value pairs. While adding a key to a dictionary is straightforward when assigning a value, there are times when you may want to add a key without specifying a value initially. In
    3 min read
  • Append a Key to a Python Dictionary
    Dictionaries are dynamic structures that allow us to add new key-value pairs to store additional information. For example, if we have a dictionary containing a student’s details and want to add a new field for their grade, we can easily append a key to the dictionary. Let's explores various ways to
    3 min read
  • Define a 3 Level Nested Dictionary in Python
    In Python, dictionaries provide a versatile way to store and organize data. Nested dictionaries, in particular, allow for the creation of multi-level structures. In this article, we'll explore the process of defining a 3-level nested dictionary and demonstrate various methods to achieve this. Define
    3 min read
  • Three Level Nested Dictionary Python
    In Python, a dictionary is a built-in data type used to store data in key-value pairs. Defined with curly braces `{}`, each pair is separated by a colon `:`. This allows for efficient representation and easy access to data, making it a versatile tool for organizing information. What is 3 Level Neste
    4 min read
  • Python | Add dictionary to tuple
    Sometimes, while working with data, we can have a problem in which we need to append to a tuple a new record which is of form of Python dictionary. This kind of application can come in web development domain in case of composite attributes. Let's discuss certain ways in which this task can be perfor
    4 min read
  • Count the Key from Nested Dictionary in Python
    In Python, counting the occurrences of keys within a nested dictionary often requires traversing through its complex structure. In this article, we will see how to count the key from the nested dictionary in Python. Count the Key from the Nested Dictionary in PythonBelow are some ways and examples b
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences