Python dict.update() function


The dict.update() method in Python is used to update a dictionary with the key-value pairs from another dictionary or an iterable of key-value pairs. This method can also be used to add new keys to the dictionary or update existing keys with new values.

Syntax

dict.update([other])
  • other: This can be another dictionary or an iterable (like a list or a tuple) of key-value pairs. The key-value pairs will be added to the dictionary, and if any keys already exist, their values will be updated.

Return Value

  • The dict.update() method does not return any value; it modifies the dictionary in place.

Example

Here are some examples to illustrate how dict.update() works:

1. Basic Example with Another Dictionary

# Original dictionary my_dict = {'a': 1, 'b': 2} # Another dictionary to update from other_dict = {'b': 3, 'c': 4} # Using update() to update my_dict with other_dict my_dict.update(other_dict) print(my_dict) # Output: {'a': 1, 'b': 3, 'c': 4}

In this example, the value of key 'b' is updated to 3, and a new key 'c' with value 4 is added.

2. Using an Iterable of Key-Value Pairs

You can also use a list of tuples or other iterables containing key-value pairs:

# Original dictionary my_dict = {'x': 10, 'y': 20} # Using a list of tuples to update update_pairs = [('y', 25), ('z', 30)] # Using update() with an iterable my_dict.update(update_pairs) print(my_dict) # Output: {'x': 10, 'y': 25, 'z': 30}

3. Using Keyword Arguments

You can also pass key-value pairs directly as keyword arguments:

# Original dictionary my_dict = {'a': 1, 'b': 2} # Updating with keyword arguments my_dict.update(c=3, d=4) print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Use Cases

  • Merging Dictionaries: Useful for merging multiple dictionaries into one.
  • Updating Values: Allows for updating existing key-value pairs without needing to check for the presence of keys.
  • Bulk Operations: Helps in efficiently performing bulk updates or additions to a dictionary.

Summary

The dict.update([other]) method is a powerful and flexible way to modify dictionaries in Python. It can merge another dictionary or iterable of key-value pairs into an existing dictionary, updating values for existing keys and adding new keys as needed. Since it modifies the dictionary in place, it's a straightforward way to manage and update data structures.