How does the update() method work in Python dictionaries?

How does the update() method work in Python dictionaries?

a) Updates the dictionary with key-value pairs from another dictionary or iterable
b) Adds a new key-value pair to the dictionary
c) Removes a key-value pair from the dictionary
d) Returns the number of key-value pairs in the dictionary

Answer:

a) Updates the dictionary with key-value pairs from another dictionary or iterable

Explanation:

The update() method in Python dictionaries updates the dictionary with key-value pairs from another dictionary or an iterable of key-value pairs. If a key already exists in the dictionary, its value is updated with the new value. If the key does not exist, it is added to the dictionary.

# Example of update() method
student = {"name": "John", "age": 20}
new_info = {"age": 21, "major": "Computer Science"}
student.update(new_info)
print(student)  # Output: {'name': 'John', 'age': 21, 'major': 'Computer Science'}

In this example, the update() method is used to add new key-value pairs and update the existing “age” key in the student dictionary.

The update() method is useful for merging dictionaries or adding multiple key-value pairs to an existing dictionary in a single operation.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top