note.nkmk.me

Iterate keys and values of dict with for loop in Python

Posted: 2020-08-25 / Tags: Python, Dictionary

In Python, to iterate the dictionary object dict with a for loop (a for statement), use keys(), values(), items(). You can also get a list of all keys and values in the dictionary with list().

  • Iterate keys of dict: keys()
  • Iterate values of dict: values()
  • Iterate key-value pairs of dict: items()

Take the following dictionary as an example.

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

You can iterate the keys by using dict directly in the for statement.

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

Iterate keys of dict: keys()

As mentioned above, you can iterate the keys by using dict directly but you can also use keys(). The result is the same, but keys() may make the intent clearer to the reader of the code.

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

The keys() method returns dict_keys. It can be converted to a list with list().

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'>

Iterate values of dict: values()

You can iterate the values by values().

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

The values() method returns dict_values. It can be converted to a list with list().

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'>
Sponsored Link

Iterate key-value pairs of dict: items()

You can iterate the key-value pairs by items().

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

It can also be received as a tuple of (key, value).

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. It can be converted to a list with list().

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'>
Sponsored Link
Share

Related Categories

Related Posts