Python - Update dictionary with other dictionary

Python - Update dictionary with other dictionary

In Python, you can update the contents of a dictionary with another dictionary using several methods. Here are the most common ones:

Using the update() Method

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

dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} dict1.update(dict2) print(dict1) # Output: {'a': 1, 'b': 3, 'c': 4} 

This method adds keys and values from dict2 to dict1, overwriting values of any existing keys.

Using Dictionary Unpacking

In Python 3.5+, you can use dictionary unpacking.

dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} dict1 = {**dict1, **dict2} print(dict1) # Output: {'a': 1, 'b': 3, 'c': 4} 

This creates a new dictionary with the contents of dict1 updated with the contents of dict2.

Using a Dictionary Comprehension

You can combine two dictionaries into a new one using a dictionary comprehension, which is more flexible as you can add conditions or process keys/values.

dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} dict1 = {k: dict2.get(k, v) for k, v in dict1.items()} dict1.update(dict2) print(dict1) # Output: {'a': 1, 'b': 3, 'c': 4} 

For Python 3.9+

Python 3.9 introduced the merge | and update |= operators for dictionaries.

dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} # Merge dictionaries dict3 = dict1 | dict2 print(dict3) # Output: {'a': 1, 'b': 3, 'c': 4} # Update dict1 in place dict1 |= dict2 print(dict1) # Output: {'a': 1, 'b': 3, 'c': 4} 

Choose the method that best suits your needs and is compatible with your Python version.


More Tags

sql-returning cqlsh client-certificates popupwindow routes build browser-cache lombok alembic driver

More Programming Guides

Other Guides

More Programming Examples