Skip to content

Q&A · Answered

How to iterate over dictionary in Python

asked 9 months, 1 week ago 2108 views 1 answer
36

What is the best way to loop through a dictionary keys and values?

1 Answer

One accepted
15

Accepted answer

Not confirmed since it was written, 9 months, 1 week ago
# Iterate over keys
for key in my_dict:
    print(key)

# Iterate over values
for value in my_dict.values():
    print(value)

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

# With enumerate
for i, (key, value) in enumerate(my_dict.items()):
    print(f"{i}: {key} = {value}")

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.