Python Dictionary update() method
Last Updated :
09 Dec, 2024
Python Dictionary update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs.
Python
# update() method in Dictionary
# Dictionary with three items
d1 = {'A': 'Geeks', 'B': 'For', }
d2 = {'B': 'Geeks', 'C': 'Python'}
# update the value of key 'B'
d1.update(d2)
# using keyword arguments
d1.update(A='Hello')
print(d1)
Output{'A': 'Hello', 'B': 'Geeks', 'C': 'Python'}
Syntax of 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
# update() method in Dictionary
# Dictionary with three items
d1 = {'A': 'Geeks', 'B': 'For', }
d2 = {'B': 'Geeks', 'C': 'Python'}
# update the value of key 'B'
d1.update(d2)
print(d1)
Output{'A': 'Geeks', 'B': 'Geeks', 'C': 'Python'}
Update with Keyword Arguments
In this example, instead of using another dictionary, we passed an iterable value to the update() function.
Python
# Dictionary with single item
d1 = {'A': 'Geeks'}
# update the Dictionary with iterable
d1.update(B='For', C='Geeks')
print(d1)
Output{'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
# Define dictionary
d = {'m': 700, 'n': 100, 't': 500}
# Key to check
key = 'm'
# Check if key exists and update
if key in d:
print(f"Key exists. Value updated to 600.")
d[key] = 600 # Directly update the value
else:
print("Key does not exist.")
print(d)
OutputKey exists. Value updated to 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
# Define dictionary
d = {'m': 700, 'n': 100, 't': 500}
# Key to check
key = 'k'
# Check if key exists and update
if key not in d:
print("Key doesn't exist. Adding a new key-value pair.")
d[key] = 600 # Direct assignment
else:
print("Key exists.")
# Print updated dictionary
print(d)
OutputKey doesn't exist. Adding a new key-value pair.
{'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 to 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 to 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 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.
Level up your coding with DSA Python in 90 days! Master key algorithms, solve complex problems, and prepare for top tech interviews. Join the Three 90 Challenge—complete 90% of the course in 90 days and earn a 90% refund. Start your Python DSA journey today!
Similar Reads
Update Dictionary with other Dictionary - Python
The task of updating a dictionary with another dictionary involves merging the key-value pairs from one dictionary into another. If a key already exists in the target dictionary, its value is updated with the value from the source dictionary. If the key does not exist in the target dictionary, it is added along with its corresponding value. For exa
3 min read
Update a Dictionary with the Values from a Dictionary List
The task of updating a dictionary with values from a list of dictionaries involves merging multiple dictionaries into one where the keys from each dictionary are combined and the values are updated accordingly. For example, we are given an dictionary d = {"Gfg": 2, "is": 1, "Best": 3} and a list of dictionaries li = [{'for': 3, 'all': 7}, {'geeks':
4 min read
How to Update a Dictionary in Python
This article explores updating dictionaries in Python, where keys of any type map to values, focusing on various methods to modify key-value pairs in this versatile data structure. Update a Dictionary in PythonBelow, are the approaches to Update a Dictionary in Python: Using with Direct assignmentUsing the dict() constructorUsing the copy() and upd
3 min read
Update a Dictionary in Python using For Loop
Updating dictionaries in Python is a common task in programming, and it can be accomplished using various approaches. In this article, we will explore different methods to update a dictionary using a for loop. Update a Dictionary in Python Using For Loop in PythonBelow are some of the approaches by which we can update a dictionary in Python by usin
3 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
Check and Update Existing Key in Python Dictionary
The task of checking and updating an existing key in a Python dictionary involves verifying whether a key exists in the dictionary and then modifying its value if it does. If the key is found, its value can be updated to a new value, if the key is not found, an alternative action can be taken, such as adding a new key-value pair or leaving the dict
4 min read
Even Values Update in Dictionary - Python
The task of updating even values in a dictionary in Python involves modifying the values associated with specific keys based on a condition, typically checking whether the values are even. For example, consider a dictionary like d = {'gfg': 6, 'is': 4, 'best': 7}. The goal is to update the values by multiplying even numbers by 3 while leaving odd n
3 min read
Variable Operations Dictionary Update - Python
The task of performing variable operations in a dictionary in Python involves updating the values associated with specific keys based on certain operations. For example, consider a scenario where x = 6 and y = 7. The goal could be to store the sum of x and y under the key 'Gfg' and the product of x and y under the key 'best'. The resulting dictiona
3 min read
Python - Dictionary Tuple Values Update
The task of updating tuple values in a dictionary involves modifying each tuple in the dictionary by applying a specific operation to its elements. In this case, the goal is to update each element of the tuple based on a given condition, such as multiplying each element by a constant. For example, given a dictionary like d = {'Gfg': (5, 6), 'is': (
3 min read
Update Nested Dictionary - Python
A nested dictionary in Python is a dictionary that contains another dictionary (or dictionaries) as its value. Updating a nested dictionary involves modifying its structure or content by:Adding new key-value pairs to any level of the nested structure.Modifying existing values associated with specific keys.Removing key-value pairs from any level wit
4 min read