36
What is the best way to loop through a dictionary keys and values?
Loading...
Q&A · Answered
What is the best way to loop through a dictionary keys and values?
Accepted answer
# 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}")Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.