Python dictionary (dict) for loop processing: keys(), values(), items()

Money and Business

To loop through the elements of a Python dictionary object with a for statement, use the following method on the dictionary object, which can also be combined with list() to obtain a list of all keys and values in the dictionary.

  • keys():For loop processing for each element key
  • values():For loop processing for each element value
  • items():For loop processing for the key and value of each element

The following dictionary object is an example.

d = {'key1': 1, 'key2': 2, 'key3': 3}

The keys can be obtained by turning the dictionary object in a for statement as it is.

for k in d:
    print(k)
# key1
# key2
# key3

keys(): For loop processing for each element key

As mentioned above, the keys can be obtained by turning the dictionary object as it is in a for statement, but the keys() method can also be used.

for k in d.keys():
    print(k)
# key1
# key2
# key3

The keys() method returns the dict_keys class. If you want to make a list, you can use the list() function.

keys = d.keys()
print(keys)
print(type(keys))
# dict_keys(['key1', 'key2', 'key3'])
# <class 'dict_keys'>

k_list = list(d.keys())
print(k_list)
print(type(k_list))
# ['key1', 'key2', 'key3']
# <class 'list'>

DICT_KEYS is capable of performing set operations.

values(): For loop processing for each element value

If you want to perform for-loop processing for each element value, use the values() method.

for v in d.values():
    print(v)
# 1
# 2
# 3

The values() method returns the dict_values class. If you want to make a list, you can use the list() function.

values = d.values()
print(values)
print(type(values))
# dict_values([1, 2, 3])
# <class 'dict_values'>

v_list = list(d.values())
print(v_list)
print(type(v_list))
# [1, 2, 3]
# <class 'list'>

Because values may overlap, the set operation of dict_values is not supported.

items(): For loop processing for the key and value of each element

If you want to perform a for loop process for both the key and value of each element, use the items() method.

for k, v in d.items():
    print(k, v)
# key1 1
# key2 2
# key3 3

(key, value)Thus, it can be received as a tuple.

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 the dict_items class. If you want to make a list, you can use the list() function. Each element is a tuple.
(key, value)

items = d.items()
print(items)
print(type(items))
# dict_items([('key1', 1), ('key2', 2), ('key3', 3)])
# <class 'dict_items'>

i_list = list(d.items())
print(i_list)
print(type(i_list))
# [('key1', 1), ('key2', 2), ('key3', 3)]
# <class 'list'>

print(i_list[0])
print(type(i_list[0]))
# ('key1', 1)
# <class 'tuple'>

DICT_ITEMS can also perform set operations.