1
0
mirror of https://github.com/jbranchaud/til synced 2026-03-04 06:58:45 +00:00
Files
til/python/iterate-over-a-dictionary.md
2026-03-04 00:20:58 -06:00

869 B

Iterate Over A Dictionary

Let's say we have a dict that contains counts of occurrences for each word in some sample text:

words_frequency = {
    "the": 4,
    "a": 3,
    "dog": 1,
    "bone": 1,
    "wants": 1,
    ...
}

Here is how we can iterate over the dict, accessing both the keys and values:

for word, count in word_frequency.items():
    print(f"- {word} appears {count} time{'' if count == 1 else 's'}")

Using the items() method, we're able to access both key and value with the for loop as it iterates.

Another approach is to loop directly on the dict which implicitly surfaces the key for iteration. This can then be used to get the value from the dict:

for word in word_frequency:
    print(f"- {word}: {word_frequency[word]}