close
The Wayback Machine - https://web.archive.org/web/20240919033339/https://www.geeksforgeeks.org/python-dictionary-update-method/
Open In App

Python Dictionary update() method

Last Updated : 21 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python Dictionary update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs.

Example:

Original dictionary : {'A': 'Geeks', 'B': 'For'}
Updated dictionary : {'A': 'Geeks', 'B': 'Geeks'}
Original dictionary : {'A': 'Geeks', 'B': 'For'}
Updated dictionary : {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}

Syntax of Python Dictionary Update Method

The dictionary update() method in Python has the following syntax:

Syntax: dict.update([other])

Parameters: This method takes either a dictionary or an iterable object of key/value pairs (generally tuples) as parameters.

Returns: It doesn’t return any value but updates the Dictionary with elements from a dictionary object or an iterable object of key/value pairs.

Python Dictionary update() Example

Let us see a few examples of the update() method to update the data of the Python dictionary.

Update with another Dictionary

Here we are updating a dictionary in Python using the update() method and passing another dictionary to it as parameters. The second dictionary is used for the updated value.

Python
# Python program to show working
# of update() method in Dictionary

# Dictionary with three items
Dictionary1 = {'A': 'Geeks', 'B': 'For', }
Dictionary2 = {'B': 'Geeks'}

# Dictionary before Updation
print("Original Dictionary:")
print(Dictionary1)

# update the value of key 'B'
Dictionary1.update(Dictionary2)
print("Dictionary after updation:")
print(Dictionary1)

Output:

Original Dictionary:
{'A': 'Geeks', 'B': 'For'}
Dictionary after updation:
{'A': 'Geeks', 'B': 'Geeks'}

Update with an Iterable

In this example, instead of using another dictionary, we passed an iterable value to the update() function.

Python
# Python program to show working
# of update() method in Dictionary

# Dictionary with single item
Dictionary1 = {'A': 'Geeks'}

# Dictionary before Updation
print("Original Dictionary:")
print(Dictionary1)

# update the Dictionary with iterable
Dictionary1.update(B='For', C='Geeks')
print("Dictionary after updation:")
print(Dictionary1)

Output
Original Dictionary:
{'A': 'Geeks'}
Dictionary after updation:
{'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}

Python Dictionary Update Value if the Key Exists

In this example, we will update the value of a dictionary in Python if the particular key exists. If the key is not present in the dictionary, we will simply print that the key does not exist.

Python
def checkKey(dict, key):
      
    if key in dict.keys():
        print("Key exist, ", end =" ")
        dict.update({'m':600})
        print("value updated =", 600)
    else:
        print("Not Exist")
dict = {'m': 700, 'n':100, 't':500}
  
key = 'm'
checkKey(dict, key)
print(dict)

Output:

Key exist,  value updated = 600
{'m': 600, 'n': 100, 't': 500}

Python Dictionary Update Value if the Key doesn’t Exist

Here, we will try to update the value of the dictionary whose key does not exist in the dictionary. In this case, the key and value will be added as the new element in the dictionary.

Python
def checkKey(dict, key):
      
    if key not in dict.keys():
        print("Key doesn't exist So, a new Key-Value pair will be created")
        dict.update({key:600})
    else:
        print("Key Exist")
dict = {'m': 700, 'n':100, 't':500}
  
key = 'k'
checkKey(dict, key)
print(dict)

Output:

Key doesn't exist So, a new Key-Value pair will be created
{'m': 700, 'n': 100, 't': 500, 'k': 600}

Python Dictionary update() method – FAQs

What Does the Update() Method Do in Dictionary in Python?

The update() method in Python dictionaries merges the contents of one dictionary into another, updating the value of keys that exist in both dictionaries and adding any keys from the second dictionary that are not in the first. If a key in the dictionary being updated already exists, its value will be replaced with the value from the dictionary being passed to update().

Example:

dict_a = {'a': 1, 'b': 2}
dict_b = {'b': 3, 'c': 4}
dict_a.update(dict_b)
print(dict_a) # Output: {'a': 1, 'b': 3, 'c': 4}

How Do You Update a Dictionary Dynamically in Python?

To dynamically update a dictionary in Python, you can add new key-value pairs or modify existing ones using subscript notation or the update() method, depending on whether you are adding a single pair or multiple pairs at once.

Example:

my_dict = {'a': 1, 'b': 2}

# Adding a new key-value pair
my_dict['c'] = 3

# Dynamically updating with another dictionary
update_dict = {'d': 4, 'e': 5}
my_dict.update(update_dict)

print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

How Do You Update All Values in a Dictionary in Python?

To update all values in a dictionary, you can use a dictionary comprehension or iterate through the dictionary and modify each value.

Example using dictionary comprehension:

my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict = {key: value * 2 for key, value in my_dict.items()}
print(my_dict) # Output: {'a': 2, 'b': 4, 'c': 6}

How to Update Multiple Keys in Dictionary in Python?

To update multiple keys in a dictionary, you can use the update() method with another dictionary that contains the new key-value pairs.

Example:

my_dict = {'a': 1, 'b': 2, 'c': 3}
updates = {'a': 10, 'c': 30}
my_dict.update(updates)
print(my_dict) # Output: {'a': 10, 'b': 2, 'c': 30}

What Is the Difference Between Update and Add in Python Dict?

  • Update: The update() method is used to modify existing key-value pairs or add new pairs from another dictionary. When using update(), if the key already exists in the dictionary, its value will be updated; if it does not exist, the key-value pair will be added.
  • Add: Adding to a dictionary typically refers to using subscript notation to insert a new key-value pair. If the key does not exist, it will be added to the dictionary. If the key already exists, its value will be replaced with the new value.

Example of adding vs. updating:

# Adding a new key-value pair
my_dict = {'a': 1, 'b': 2}
my_dict['c'] = 3 # Adds 'c': 3

# Updating existing or adding new key-value pairs
more_updates = {'b': 20, 'd': 40}
my_dict.update(more_updates) # Updates 'b' and adds 'd'

print(my_dict) # Output: {'a': 1, 'b': 20, 'c': 3, 'd': 40}

In summary, update() can add or modify multiple items based on another dictionary, whereas adding typically refers to inserting or modifying a single item directly.



Previous Article
Next Article

Similar Reads

Python: Update Nested Dictionary
A Dictionary in Python works similar to the Dictionary in the real world. Keys of a Dictionary must be unique and of immutable data types such as Strings, Integers, and tuples, but the key-values can be repeated and be of any type. Refer to the below article to get the idea about dictionaries: Python Dictionary Nested Dictionary: The nested diction
6 min read
How to Fix "ValueError: dictionary update sequence element #0 has length X; 2 is required" in Python
The "ValueError: dictionary update sequence element #0 has length X; 2 is required" error typically occurs when trying to update a dictionary with a sequence that does not contain exactly two elements for each key-value pair. This article explains the causes of this error and provides the solutions to fix it. Understanding the ErrorThe "ValueError:
3 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
Python Counter.update() Method
Python's Counter is a subclass of the dict class and provides a convenient way to keep track of the frequency of elements in an iterable. The Counter.update() method is particularly useful for updating the counts of elements in a Counter object based on another iterable or another Counter object. In this article, we will understand about the Counte
2 min read
MongoDB Python | Insert and Update Data
Prerequisites : MongoDB Python Basics We would first understand how to insert a document/entry in a collection of a database. Then we would work on how to update an existing document in MongoDB using pymongo library in python. The update commands helps us to update the query data inserted already in MongoDB database collection. Insert data We would
3 min read
Python SQLite - Update Data
In this article, we will discuss how we can update data in tables in the SQLite database using Python - sqlite3 module. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using UPDATE statement as per our requirement. Syntax: UPDATE table_name SET col
7 min read
Python | Pandas Series.update()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object suppo
2 min read
Update column value of CSV in Python
Prerequisites: Pandas In this article, we will discuss ways in which the value(s) of a column can be updated. The best and the optimal way to update any column value of a CSV is to use the Pandas Library and the DataFrame functions. Link for the CSV file in use - Click here Method 1 Approach Import moduleOpen CSV file and read its dataFind column t
3 min read
Python MySQL - Update Query
A connector is employed when we have to use MySQL with other programming languages. The work of MySQL-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. Update Clause The update is used to change the existing values in a database. By using u
2 min read
Matplotlib.axes.Axes.update() in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. matplotlib.axes.Axes.update() Function The Axes.up
2 min read
Matplotlib.artist.Artist.update() in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Artist class contains Abstract base class for objects that render into a FigureCanvas. All visible elements in a figure are subclasses of Artist. matplotlib.artist.Artist.update() method The update() method in artist module of matplotlib library is
2 min read
How to update data in a Collection using Python?
MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. MongoDB offers high speed, high availability, and high scalability. Updating Data in MongoDB We can update data in a collection using update_one() method and update_many() method. update_one() update_one() method update first occurrence i
2 min read
How to get COVID 19 update using Covid module in Python?
A new Python library which tells the COVID-19 related information (country-wise) and it show that how many cases of confirmed, active, deaths, recovered found in that particular Country. Requirement: You have python package named COVID and python >= 3.6 Installation: pip install covid Dependencies: pydantic requests Example: from covid import Co
3 min read
Matplotlib.axis.Axis.update() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. Matplotlib.axis.Axis.update() Function The Axis.update() function in axis module of matplotlib library is used to update this art
2 min read
Matplotlib.axis.Tick.update() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. Matplotlib.axis.Tick.update() Function The Tick.update() function in axis module of matplotlib library is used to update this art
2 min read
Python SQLite - Update Specific Column
In this article, we will discuss how to update a specific column of a table in SQLite using Python. In order to update a particular column in a table in SQL, we use the UPDATE query. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple columns using UPDATE stat
3 min read
Python MariaDB - Update Query using PyMySQL
MariaDB is an open-source Database Management System and its predecessor to MySQL. The pymysql client can be used to interact with MariaDB similar to that of MySQL using Python. In this article, we will look into the process of using the UPDATE query on a table of the database using pymysql. The update is used to change the existing values in a dat
2 min read
How to update a pickle file in Python?
Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on a disk. What pickle does is that it “serializes” the object first before writing it to file. Pickling is a way to convert a python object (list, dict, etc.) into a character stream. The idea is th
3 min read
PostgreSQL Python - Update Data in Table
In this article, we are going to see how to update existing data in PostgreSQL tables using the pyscopg2 module in Python. In PostgreSQL, the UPDATE TABLE with where clause is used to update the data in the existing table from the database. Syntax: UPDATE <table_name> SET column1 = value1, column2 = value2,..... WHERE [condition] To execute a
2 min read
How to Update all the Values of a Specific Column of SQLite Table using Python ?
In this article, we are going to update all the values of a specific column of a given SQLite table using Python. In order to update all the columns of a particular table in SQL, we use the UPDATE query. The UPDATE statement in SQL is used to update the data of an existing table in the database. We can update single columns as well as multiple colu
3 min read
Python PostgreSQL - Update Table
In this article, we will see how to Update data in PostgreSQL using python and Psycopg2. The update command is used to modify the existing record in the table. By default whole records of the specific attribute are modified, but to modify some particular row, we need to use the where clause along with the update clause. Syntax for Update Clause UPD
2 min read
Update multiple rows in same query in PostgreSQL using Pyscopg2-Python
In this article, we are going to update multiple rows in the same query in PostgreSQL using Pyscopg2in Python. We can update multiple values at once by using the update clause from PostgreSQL. First, we import the psycopg2 package and establish a connection to a PostgreSQL database using the pyscopg2.connect() method. Syntax of update clause:UPDATE
1 min read
Python SQLAlchemy - Update table structure
In this article, we are going to update the structure of the table using the sqlalchemy module. The structure of the table includes name of columns, the datatype of columns, constraints, keys, etc which we are going to update in this post. Installing the requirements: Let us first install the SQLAlchemy module by running the following pip command i
3 min read
Dynamically Update Multiple Rows with PostgreSQL and Python
In this tutorial, we will explore how to dynamically update multiple rows in a PostgreSQL database using Python. By the end of this tutorial, you'll have a solid understanding of how to write efficient Python code that interacts with PostgreSQL to update multiple rows in a database. We'll cover topics such as connecting to a PostgreSQL database, ex
3 min read
Python Set | update()
Python update() function in set adds elements from a set (passed as an argument) to the set. If the element is present in both of the sets then the element comes only one time in the updated set. Python Set update() Method SyntaxSyntax : set1.update(set2) Here set1 is the set in which set2 will be added. Parameters : Update() method takes any numbe
3 min read
Set update() in Python to do union of n arrays
We are given n arrays of any size which may have common elements, we need to combine all these arrays in such a way that each element should occurs only once and elements should be in sorted order? Examples: Input : arr = [[1, 2, 2, 4, 3, 6], [5, 1, 3, 4], [9, 5, 7, 1], [2, 4, 1, 3]] Output : [1, 2, 3, 4, 5, 6, 7, 9] A simple solution for this prob
2 min read
Update JSON Key Name in Python
Working with JSON data is a common task in Python, and there are various scenarios where you might need to update the key names within a JSON object. In this article, we will explore five different simple and generally used methods to achieve this task, accompanied by code examples. How to Update Json Key Name in Python?Below, are the ways To Updat
3 min read
How to update existing table rows in SQLAlchemy in Python?
In this article, we are going to see how to use the UPDATE statement in SQLAlchemy against a PostgreSQL database in Python. Creating table for demonstration:Import necessary functions from the SQLAlchemy package. Establish connection with the PostgreSQL database using create_engine() function as shown below, create a table called books with columns
2 min read
Update Jupyter Notebook to the Latest Python Version
To take advantage of the latest features and improvements in Python, it is important to keep your Jupyter Notebook updated with the latest Python version. This article will guide you through the process of updating Jupyter Notebook to the latest Python version. Note: Let's say if we want to Download Install from Python 3.7 to 3.11: Checking the Cur
3 min read
Latest Update on Python 4.0
Python remains one of the most popular programming languages in 2024, known for its simplicity, versatility, and extensive ecosystem. As Python continues to evolve with regular updates to the Python 3.x series, speculation about the potential release of Python 4.0 has surfaced. However, recent statements from Guido van Rossum, the creator of Python
6 min read