Programming and IT
Python: dictionaries
A dictionary stores key–value pairs and finds a value by its key in constant time, however large it grows. It is the workhorse for counting, grouping and settings. Below: creating dictionaries, safe access, iteration and the places where a dictionary does not behave the way people expect.
In this article
Creating a dictionary and what a key must be#
=
= # a dictionary, not a set
=
# 120 2
A key can only be an immutable (hashable) value: a string, a number, a tuple, a
boolean. A list cannot be a key — trying gives TypeError: unhashable type: 'list'. A value can be anything, including another dictionary.
Insertion order is preserved: since Python 3.7 this is not an implementation accident but a language guarantee. Iterating over a dictionary yields the keys in the order they were added.
Access without KeyError#
Square brackets raise KeyError when the key is missing. When a missing key is a
normal situation, use get:
# None
# 0
# False
= 90 # adding also uses brackets
The in operator checks keys, not values; for values you need
in prices.values().
The related setdefault method returns the value for a key, and if the key is
missing it stores the given default and returns that. It is handy for grouping:
=
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}
Iteration and the three views#
# ['tea', 'coffee', 'cocoa']
# 460
keys(), values() and items() return views, not lists: they look at the live
dictionary and reflect changes. If you really need a list, wrap it in list().
Sorting a dictionary gives you a list of pairs, not a dictionary:
=
# [('coffee', 250), ('tea', 120), ('cocoa', 90)]
# back to a dictionary, if you need one
Changing, deleting, merging#
# {'tea': 130, 'coffee': 250, 'cocoa': 90, 'juice': 100}
=
# 90
# 0 instead of KeyError
del
update overwrites existing keys and adds new ones. Since Python 3.9 there is a
merge operator: a | b gives a new dictionary, and a |= b changes a in place.
When a key appears in both, the right-hand dictionary wins.
A dictionary comprehension is built like a list comprehension, but with a pair separated by a colon:
=
# {0: 0, 1: 1, 2: 4, 3: 9}
=
# 3
Where it breaks#
Adding while iterating. Changing the size of a dictionary inside a loop over
it raises RuntimeError: dictionary changed size during iteration. Collect the
changes separately or iterate over a copy: for k in list(d).
Duplicate keys in a literal. {"a": 1, "a": 2} is not an error — you end up
with {'a': 2}: the last assignment silently wins.
True and 1 are the same key. Keys are compared by value, and 1 == True,
so {1: "one", True: "yes"} collapses into a single item with the value "yes".
Counting with get. A typical task is counting frequencies. Without a
dictionary it grows into a dozen lines; with one it fits in three:
=
= + 1
# {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}
Try it yourself: count word frequencies in a text and print the three most common
using sorted with key. For the text handling you will need
Python strings, and when order matters more than keys,
use Python lists.
Step-by-step plan
- A settings dictionaryCreate a dictionary of five pairs, print a value by key and the length.
- Safe accessCompare d["none"] with d.get("none", 0): the first call should raise KeyError.
- Iterate with itemsPrint every pair as "key → value" using items().
- Character frequenciesCount how many times each character appears in a string using get.
- Sort by valueSort the pairs by value in descending order and print the first three.
Start learning this in your own space
The plan goes into your repository: tick off stages, keep notes — the change history shows how far you have come.
Check yourself
1.What does this print: d = {"a": 1}; print(d.get("b", 0))?
2.What does print(len({"a": 1, "b": 2, "a": 3})) print?
3.What does this print: d = {"x": 1}; print("x" in d, 1 in d)?
4.How many times does the letter "a" appear in the string "abracadabra"?
Sources
-
Dictionaries in the Python tutorialThe Dictionaries section with iteration examplesfree
-
The dict type referenceEvery dictionary method and the rules for keysfree
-
collections.CounterA ready-made dictionary for counting frequenciesfree
Was this helpful?