Update a Dictionary in Python
Below, are the approaches to Update a Dictionary in Python:
- Using with Direct assignment
- Using the dict() constructor
- Using the copy() and update() methods
- Using the **kwargs syntax with a function
Update a Dictionary Using the Direct Assignment
This below apporach code updates a dictionary (dictionary1) by directly assigning a new value to an existing key (“b”) and adding a new key-value pair (“c”: 4), showcasing how to modify and extend dictionaries using direct assignment. The final updated dictionary is then printed.
Python
# original dictionary dictionary1 = { "a" : 1 , "b" : 2 } # update value for an exisitng key dictionary1[ "b" ] = 3 # add a new key-value pair dictionary1[ "c" ] = 4 # printing result dicitonary print (dictionary1) |
{'a': 1, 'c': 4, 'b': 3}
Update a Dictionary Using dict() constructor
The below apporach code updates a dictionary using the dict() constructor by passing a sequence of key-value pairs as arguments to create a new dictionary or by using an existing dictionary and adding new key-value pairs to it.
Python
# Creating a new dictionary main_dict = dict (a = 1 , b = 2 ) # Updating the dictionary using the dict() constructor updated_dict = dict (main_dict, c = 3 , d = 4 ) print (updated_dict) |
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
Update a Dictionary Using the copy() and update() methods
The below approach code updates a dictionary (main_dict) by creating a copy (updated_dict) using the copy() method, and then using the update() method to add new key-value pairs (‘c’: 3, ‘d’: 4) to the copied dictionary. The final updated dictionary is then printed.
Python
main_dict = { 'a' : 1 , 'b' : 2 } # Create a copy of the original dictionary updated_dict = main_dict.copy() # Update the copied dictionary with new key-value pairs updated_dict.update({ 'c' : 3 , 'd' : 4 }) print (updated_dict) |
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
Update a Dictionary Using the **kwargs with a function
The below approach code uses the **kwargs syntax within a function. This approach allows us to pass key-value pairs as keyword arguments to a function and update the dictionary using these arguments.
Python
# Define a function that takes a dictionary and **kwargs def update_dict(input_dict, * * kwargs): # Update the input_dict with the provided keyword arguments input_dict.update(kwargs) # Create an initial dictionary dict = { 'a' : 1 , 'b' : 2 } # Call the update_dict function with **kwargs to update the dictionary update_dict( dict , c = 3 , d = 4 ) # Print the updated dictionary print ( dict ) |
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
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.