An element in a dictionary is also called an item. Each item is made up of a key and a value.
The three dictionary methods; items()
, keys()
and values()
retrieves all items, keys and values respectively.
items()
- Returns an iterable of all key-value pairs(items) present in the dictionary.keys()
- Returns an iterable with all the keys in the dictionary.values()
- Returns an iterable with all the values in the dictionary.
items() - Get all items present in a dictionary
To get an iterable containing all the items present in a dictionary, use the items()
method. The syntax is as shown below:
d.items()
copy
The method does not take any argument.
The items()
method is useful when it comes to iterating over the dictionary items. Remember that iterating over a dictionary only yields its keys, so using the items()
method allows you to access both the key and its corresponding value in one iteration.
In the above example, we used the for loop to iterate over a dictionary. As you can see, only the keys are returned. Now consider the same example with the items()
method.
As you can see, iterating through the items()
object returns tuples in the form (key, value)
for each dictionary item.
keys() - get all keys of a dictionary
The keys()
method returns an object containing all the keys present in a dictionary.
it has the following syntax:
d.keys()
copy
The method does not take any arguments.
You can iterate through the returned object to get individual keys at each iteration.
values() - get all values in the dictionary
Finally, the values()
method returns an object containing all the keys in the dictionary. It has the following syntax:
d.values()
copy
The method does not take arguments.
Conclusion
- Use
items()
to get an iterable of two length tuples, where each tuple contains a key and a value of a dictionary item. - Use
keys()
to get an iterable of all the keys present in a dictionary. - use
values()
to get an iterable of all the values present in a dictionary.