Iterate Over Dictionary Keys, Values, and Items in Python
In Python, you can iterate over a dictionary (dict
) using the keys()
, values()
, or items()
methods in a for
loop. You can also convert the keys, values, or items of a dictionary into a list using the list()
function.
See the following article for the basics of for
loops in Python.
Consider the following dictionary as an example.
d = {'key1': 1, 'key2': 2, 'key3': 3}
You can iterate over dictionary keys simply by using the dictionary itself in a for
loop. To get a list of all its keys, simply pass a dictionary to list()
.
for k in d:
print(k)
# key1
# key2
# key3
print(list(d))
# ['key1', 'key2', 'key3']
print(type(list(d)))
# <class 'list'>
Iterate over dictionary keys: keys()
As mentioned above, you can iterate over dictionary keys by directly using the dictionary object, but you can also use keys()
. The result is the same, but using keys()
can make your code's intention clearer to the reader.
for k in d.keys():
print(k)
# key1
# key2
# key3
The keys()
method returns dict_keys
, which can be converted to a list using list()
.
print(d.keys())
# dict_keys(['key1', 'key2', 'key3'])
print(type(d.keys()))
# <class 'dict_keys'>
print(list(d.keys()))
# ['key1', 'key2', 'key3']
print(type(list(d.keys())))
# <class 'list'>
You can use dict_keys
to perform set operations. See the following article for details.
Iterate over dictionary values: values()
To iterate over dictionary values, use the values()
method.
for v in d.values():
print(v)
# 1
# 2
# 3
The values()
method returns dict_values
, which can be converted to a list using list()
.
print(d.values())
# dict_values([1, 2, 3])
print(type(d.values()))
# <class 'dict_values'>
print(list(d.values()))
# [1, 2, 3]
print(type(list(d.values())))
# <class 'list'>
Iterate over dictionary key-value pairs: items()
To iterate over dictionary key-value pairs, use the items()
method.
for k, v in d.items():
print(k, v)
# key1 1
# key2 2
# key3 3
You can also receive the key-value pairs as (key, value)
tuples in the loop.
for t in d.items():
print(t)
print(type(t))
print(t[0])
print(t[1])
print('---')
# ('key1', 1)
# <class 'tuple'>
# key1
# 1
# ---
# ('key2', 2)
# <class 'tuple'>
# key2
# 2
# ---
# ('key3', 3)
# <class 'tuple'>
# key3
# 3
# ---
The items()
method returns dict_items
, which can be converted to a list using list()
.
print(d.items())
# dict_items([('key1', 1), ('key2', 2), ('key3', 3)])
print(type(d.items()))
# <class 'dict_items'>
print(list(d.items()))
# [('key1', 1), ('key2', 2), ('key3', 3)]
print(type(list(d.items())))
# <class 'list'>
print(type(list(d.items())[0]))
# <class 'tuple'>
You can also use dict_items
to perform set operations. See the following article for details.