Sobes.tech
Junior

What does iterating over a dictionary in Python return?

sobes.tech AI

Answer from AI

Iterating over a dictionary in Python by default returns the dictionary's keys.

This behavior can be changed using special methods:

  • dict.keys(): returns an iterator over the keys.
  • dict.values(): returns an iterator over the values.
  • dict.items(): returns an iterator over (key, value) tuples.
# Example of iterating over keys
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict:
    print(key)

# Example of iterating over values
for value in my_dict.values():
    print(value)

# Example of iterating over key-value pairs
for key, value in my_dict.items():
    print(f"{key}: {value}")

Here is a table with examples:

Method What it returns in each iteration Usage example
(by default) Key for k in my_dict:
dict.keys() Key for k in my_dict.keys():
dict.values() Value for v in my_dict.values():
dict.items() Tuple (key, value) for k, v in my_dict.items():