From c1f046d1961cceb30775828221ee5ff26b5c936b Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Wed, 4 Mar 2026 00:20:58 -0600 Subject: [PATCH] Add Iterate Over A Dictionary as a Python TIL --- README.md | 3 ++- python/iterate-over-a-dictionary.md | 34 +++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 python/iterate-over-a-dictionary.md diff --git a/README.md b/README.md index b3ff05b..c165851 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ working across different projects via [VisualMode](https://www.visualmode.dev/). For a steady stream of TILs, [sign up for my newsletter](https://visualmode.kit.com/newsletter). -_1750 TILs and counting..._ +_1751 TILs and counting..._ See some of the other learning resources I work on: @@ -1047,6 +1047,7 @@ If you've learned something here, support my efforts writing daily TILs by - [Easy Key-Value Aggregates With defaultdict](python/easy-key-value-aggregates-with-defaultdict.md) - [Install With PIP For Specific Interpreter](python/install-with-pip-for-specific-interpreter.md) - [Iterate First N Items From Enumerable](python/iterate-first-n-items-from-enumerable.md) +- [Iterate Over A Dictionary](python/iterate-over-a-dictionary.md) - [Keep A Tally With collections.Counter](python/keep-a-tally-with-collections-counter.md) - [Load A File Into The Python REPL](python/load-a-file-into-the-python-repl.md) - [Override The Boolean Context Of A Class](python/override-the-boolean-context-of-a-class.md) diff --git a/python/iterate-over-a-dictionary.md b/python/iterate-over-a-dictionary.md new file mode 100644 index 0000000..03b65d9 --- /dev/null +++ b/python/iterate-over-a-dictionary.md @@ -0,0 +1,34 @@ +# Iterate Over A Dictionary + +Let's say we have a `dict` that contains counts of occurrences for each word in +some sample text: + +```python +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: + +```python +for word, count in word_frequency.items(): + print(f"- {word} appears {count} time{'' if count == 1 else 's'}") +``` + +Using the +[`items()`](https://docs.python.org/3/library/stdtypes.html#dict.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`: + +```python +for word in word_frequency: + print(f"- {word}: {word_frequency[word]} +```