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:
Add new keys to a dictionary in Python
Next article icon

How to Add Values to Dictionary in Python

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

The task of adding values to a dictionary in Python involves inserting new key-value pairs or modifying existing ones. A dictionary stores data in key-value pairs, where each key must be unique. Adding values allows us to expand or update the dictionary's contents, enabling dynamic manipulation of data.

For example, if we start with a dictionary a = {0: 'Carrot', 1: 'Raddish'}, we can add a new key-value pair like a[2] = 'Brinjal', resulting in the dictionary {0: 'Carrot', 1: 'Raddish', 2: 'Brinjal'}.

Using union operator

union operator (|) is a efficient way to add values by merging dictionaries as it creates a new dictionary with the combined key-value pairs, leaving the original dictionaries unchanged.

Python
a = {0: 'Carrot', 1: 'Raddish'} b = {2: 'Brinjal', 3: 'Potato'}  res = a | b print(res) 

Output
{0: 'Carrot', 1: 'Raddish', 2: 'Brinjal', 3: 'Potato'} 

Explanation: a | b combines all key-value pairs from a and b, with values from b overwriting those in a if duplicate keys exist .

Table of Content

  • Using unpacking
  • Using update()
  • Using dictionary comprehension
  • Using assignment operator

Using unpacking

** unpacking syntax expands dictionaries into key-value pairs ,making it a clean and effective way to merge dictionaries into a new one .

Python
a = {0: 'Carrot', 1: 'Raddish'} b = {2: 'Brinjal', 3: 'Potato'}  res = {**a, **b} print(res) 

Output
{0: 'Carrot', 1: 'Raddish', 2: 'Brinjal', 3: 'Potato'} 

Explanation: {**a, **b} merges dictionaries by unpacking all key-value pairs from a and b, with values from b overwriting those in a if duplicate keys exist.

Using update()

update() method allows us to add multiple key-value pairs from another dictionary or an iterable of key-value pairs to an existing dictionary. If a key exists, its value will be updated.

Python
a = {0: 'Carrot', 1: 'Raddish'} b = {2: 'Brinjal', 3: 'Potato'}  res = a.copy()  #  creates a shallow copy of dictionary `a` res.update(b) print(res) 

Output
{0: 'Carrot', 1: 'Raddish', 2: 'Brinjal', 3: 'Potato'} 

Explanation: res.update(b) merges b into res by adding all key-value pairs, updating existing keys in res if duplicates exist, and appending new keys from b .

Using dictionary comprehension

This method iterates over key-value pairs from one or more dictionaries and constructs a new dictionary. While less efficient, it is useful when we need to apply logic while adding values.

Python
a = {0: 'Carrot', 1: 'Raddish'} b = {2: 'Brinjal', 3: 'Potato'}  res = {k: v for d in (a, b) for k, v in d.items()} print(res) 

Output
{0: 'Carrot', 1: 'Raddish', 2: 'Brinjal', 3: 'Potato'} 

Explanation: dictionary comprehension merges a and b by iterating over both dictionaries and collecting key-value pairs into a new dictionary.

Using assignment operator

This is the simplest way to add a single key-value pair to a dictionary. If the key already exists, its value will be updated.

Python
a = {0: 'Carrot', 1: 'Raddish'}  # Adding a single key-value pair a[2] = 'Brinjal' print(a) 

Output
{0: 'Carrot', 1: 'Raddish', 2: 'Brinjal'} 

Explanation: a[2] = 'Brinjal' adds key 2 with the value 'Brinjal' to dictionary a.


Next Article
Add new keys to a dictionary in Python

A

abhishekm482g
Improve
Article Tags :
  • Python
  • Python Programs
Practice Tags :
  • python

Similar Reads

  • Python Change Dictionary Item
    A common task when working with dictionaries is updating or changing the values associated with specific keys. This article will explore various ways to change dictionary items in Python. 1. Changing a Dictionary Value Using KeyIn Python, dictionaries allow us to modify the value of an existing key.
    3 min read
  • Python Remove Dictionary Item
    Sometimes, we may need to remove a specific item from a dictionary to update its structure. For example, consider the dictionary d = {'x': 100, 'y': 200, 'z': 300}. If we want to remove the item associated with the key 'y', several methods can help achieve this. Let’s explore these methods. Using po
    3 min read
  • Get length of dictionary in Python
    Python provides multiple methods to get the length, and we can apply these methods to both simple and nested dictionaries. Let’s explore the various methods. Using Len() FunctionTo calculate the length of a dictionary, we can use Python built-in len() method. It method returns the number of keys in
    3 min read
  • Python - Value length dictionary
    Sometimes, while working with a Python dictionary, we can have problems in which we need to map the value of the dictionary to its length. This kind of application can come in many domains including web development and day-day programming. Let us discuss certain ways in which this task can be perfor
    4 min read
  • Python - Dictionary values String Length Summation
    Sometimes, while working with Python dictionaries we can have problem in which we need to perform the summation of all the string lengths which as present as dictionary values. This can have application in many domains such as web development and day-day programming. Lets discuss certain ways in whi
    4 min read
  • Calculating the Product of List Lengths in a Dictionary - Python
    The task of calculating the product of the lengths of lists in a dictionary involves iterating over the dictionary’s values, which are lists and determining the length of each list. These lengths are then multiplied together to get a single result. For example, if d = {'A': [1, 2, 3], 'B': [4, 5], '
    3 min read
  • Python - Access Dictionary items
    A dictionary in Python is a useful way to store data in pairs, where each key is connected to a value. To access an item in the dictionary, refer to its key name inside square brackets. Example: [GFGTABS] Python a = {"Geeks": 3, "for": 2, "geeks": 1} #Access the value a
    3 min read
  • Dictionary items in value range in Python
    In this article, we will explore different methods to extract dictionary items within a specific value range. The simplest approach involves using a loop. Using LoopThe idea is to iterate through dictionary using loop (for loop) and check each value against the given range and storing matching items
    2 min read
  • Python | Ways to change keys in dictionary
    Given a dictionary, the task is to change the key based on the requirement. Let's see different methods we can do this task in Python. Example: initial dictionary: {'nikhil': 1, 'manjeet': 10, 'Amit': 15} final dictionary: {'nikhil': 1, 'manjeet': 10, 'Suraj': 15} c: Amit name changed to Suraj.Metho
    3 min read
  • Python Program to Swap dictionary item's position
    Given a Dictionary, the task is to write a python program to swap positions of dictionary items. The code given below takes two indices and swap values at those indices. Input : test_dict = {'Gfg' : 4, 'is' : 1, 'best' : 8, 'for' : 10, 'geeks' : 9}, i, j = 1, 3 Output : {'Gfg': 4, 'for': 10, 'best':
    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