Python dictionary and for loop: How to iterate the key and value of a dictionary in Python

You can iterate dictionary keys by using the for-in statement.

d = {'book': 24, 'pen': '5'}

for k in d:
    print(k)

# book
# pen

In that style, only keys are printed. If d is a list, all the elements are iterated and printed. How can we iterate each key and value of a dictionary? The following is a simple solution.

d = {'book': 24, 'pen': '5'}

for k, v in d.items():
    print(k)
    print(v)

# book
# 24
# pen
# 5

d.items() is a kind of list and has pairs of the dictionary. Each pair is a tuple. k, v is a pair, k is a key and v is a value.

What is d.items() and the item of d.items()?

d.items() is a dict_items object so not a list. It has pairs of a dictionary.

d = {'book': 24, 'pen': '5'}

print(d.items())  # dict_items([('book', 24), ('pen', '5')])
print(type(d.items()))  # <class 'dict_items'>

for i in d.items():
    print(i)

# ('book', 24)
# ('pen', '5')

The item of d.items() is a Python tuple of key and value.

If not using d.items()...

The below is incorrect and Python raises ValueError exception.

d = {'book': 24, 'pen': '5'}

for k, v in d:
    print(k)
    print(v)

# ValueError: too many values to unpack (expected 2)

Python Dictionary

Python Tutorial