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

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

a) Returns a view object that displays a list of dictionary’s key-value tuple pairs
b) Adds a new key-value pair to the dictionary
c) Removes a key-value pair from the dictionary
d) Reverses the order of key-value pairs in the dictionary

Answer:

a) Returns a view object that displays a list of dictionary’s key-value tuple pairs

Explanation:

The items() method in Python dictionaries returns a view object that displays a list of the dictionary’s key-value pairs as tuples. This method is useful when you need to iterate over a dictionary and access both the keys and their corresponding values.

# Example of items() method
student = {"name": "John", "age": 20, "major": "Computer Science"}
for key, value in student.items():
    print(f"{key}: {value}")
# Output:
# name: John
# age: 20
# major: Computer Science

In this example, the items() method is used to iterate over the dictionary student, printing each key-value pair.

The items() method is especially useful for looping through dictionaries when you need to access both the key and value simultaneously.

Leave a Comment

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

Scroll to Top