Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Python Dictionary update() method

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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

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

Example #1: Update with another Dictionary

Python3




# 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'}

Example #2: Update with an iterable

Python3




# 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'}

Example #3: Python dictionary update value if the key exists

Python3




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}

Example #4: Python dictionary update value if the key doesn’t exists

Python3




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}

Note: A new Key value pair gets created automatically if given Key is not present in the Dictionary. 


My Personal Notes arrow_drop_up
Last Updated : 20 Feb, 2023
Like Article
Save Article
Similar Reads
Related Tutorials