There are lots of different ways to merge dictionaries in the Python.
Here are the methods you will learn about:
- dict.update()
- **
- the | Union Operator
Let’s start with the update() method!
Using dict.update()
>>> first_dictionary = {"name": "Mike", "occupation": "Python Teacher"} >>> second_dictionary = {"location": "Iowa", "hobby": "photography"} >>> first_dictionary.update(second_dictionary) >>> first_dictionary {'name': 'Mike', 'occupation': 'Python Teacher', 'location': 'Iowa', 'hobby': 'photography'}
Merging with **
When you use the double-asterisk, it is sometimes called “unpacking”, “expanding” or “splatting” a dictionary.
Here is how you can use ** to merge 2 dictionaries:
>>> first_dictionary = {"name": "Mike", "occupation": "Python Teacher"} >>> second_dictionary = {"location": "Iowa", "hobby": "photography"} >>> merged_dictionary = {**first_dictionary, **second_dictionary} >>> merged_dictionary {'name': 'Mike', 'occupation': 'Python Teacher', 'location': 'Iowa', 'hobby': 'photography'}
Merging with the Union Operator
Here is how you can use the union operator to merge two dictionaries:
>>> first_dictionary = {"name": "Mike", "occupation": "Python Teacher"} >>> second_dictionary = {"location": "Iowa", "hobby": "photography"}>>> merged_dictionary = first_dictionary | second_dictionary>>> merged_dictionary{'name': 'Mike', 'occupation': 'Python Teacher', 'location': 'Iowa', 'hobby': 'photography'}
Twitter: @pythonprogrammi - python_pygame