Looping over dicts
Once your data is in a dict, you'll often want to walk through every entry. Python gives you three clean ways to loop.
Loop over keys
By default, looping over a dict gives you its keys:
Python
Loop over values
Use .values() when you only care about the values:
Python
Loop over key–value pairs
Use .items() to get both the key and the value at once:
Python
Note the str(value) — you must convert numbers to strings before joining them with +.
Key takeaways
- Looping a dict directly gives you its keys.
.values()loops over values only..items()gives you(key, value)pairs — use it when you need both.
No comments yet. Add the first comment to start the discussion.