Python dictionary Method - items()
The items()
method is a built-in dictionary method in Python that returns a view object that contains the key-value pairs of the dictionary as tuples. The order of the tuples is not guaranteed. You can use this method to loop over the key-value pairs of a dictionary.
Here's the syntax for the items()
method:
items = my_dict.items()
Here, my_dict
is the dictionary to get the key-value pairs from, and items
is the view object that contains the tuples.
Here's an example:
# create a dictionary my_dict = {'apple': 3, 'banana': 2, 'cherry': 5} # get the key-value pairs as tuples items = my_dict.items() # print the key-value pairs for key, value in items: print(key, value)
Output:
apple 3 banana 2 cherry 5
In this example, we create a dictionary my_dict
with three key-value pairs. We then use the items()
method to get a view object that contains the tuples of key-value pairs. We loop over the tuples using a for
loop and print each key and value.
The items()
method is useful when you need to loop over the key-value pairs of a dictionary. You can also use the items()
method to create a new dictionary that contains a subset of the key-value pairs of the original dictionary. For example:
# create a dictionary my_dict = {'apple': 3, 'banana': 2, 'cherry': 5} # create a new dictionary with only the items where the value is greater than 2 new_dict = {k: v for k, v in my_dict.items() if v > 2} # print the new dictionary print(new_dict)
Output:
{'apple': 3, 'cherry': 5}
In this example, we use the items()
method to loop over the key-value pairs of the my_dict
dictionary. We create a new dictionary using a dictionary comprehension that includes only the key-value pairs where the value is greater than 2. The resulting dictionary contains only the key-value pairs for 'apple'
and 'cherry'
.