In this tutorial, we’ll learn how to use Python dictionary update() method with the help of multiple Python code examples.
Introduction: Python Dictionary update() Method
This method is used to update a Python dictionary by adding or updating values to it using another dictionary or by using an iterable having key/value pairs.
Syntax of update() Method
dictionaryName.update(data)
- This method takes either a dictionary as an argument or a key/value pairs iterable object(e.g. tuple).
- If the arguments are not passed then no updates will take place in dictionary.
- Python dictionary update method return None. It just updates the specified dictionary.
Example 1: Updating Values of Dictionary
dictItems={'name':'Apple','color':'Red'} dictItems.update({'name':'Banana'}) print(dictItems)
Output
{'name': 'Banana', 'color': 'Red'}
As you can see in the above code that we’ve changed the value of key(name) from apple to banana. You can either pass dictionary directly like that or you can assign it to some dictionary variable. See below code:
dictItems={'name':'Apple','color':'Red'} newDict={'name':'Banana'} dictItems.update(newDict) print(dictItems)
Output
{'name': 'Banana', 'color': 'Red'}
Example 2: adding Item to Dictionary using update() Method
dictItems={'name':'Apple','color':'Red'} newDict={'number':28} dictItems.update(newDict) print(dictItems)
Output
{'name': 'Apple', 'color': 'Red', 'number': 28}
If the specified key passed to the Python dictionary update method is not found in the dictionary, then the same item(key and value pair) will be added to this dictionary.
Example 3: Pass Tuple using update() Method
dictItems={'name':'Apple','color':'Red'} tuplesList=[('color','Yellow'),('quantity',7000)] dictItems.update(tuplesList) print(dictItems)
Output
{'name': 'Apple', 'color': 'Yellow', 'quantity': 7000}
We’ve updated the current item and also added a new item to the existing dictionary.
Example 4: update() Method Return None
dictItems={'name':'Apple'} print(dictItems.update({'name':'Pineapple'})) // return None print(dictItems) // updated
Output
None // update method return none {'name': 'Pineapple'} // dictionary is updated
You can see that the update method does not return anything. It just updates the existing Python dictionary.
Conclusion
To conclude this tutorial, now you have a detailed practical knowledge of how to use Python dictionary update method. I’ll be very glad to receive your valuable feedback on this post. Thank you for reading it.