Dictionaries & sets
Count, group and look up data with dicts and remove duplicates with sets.
By Invicly Tech, , in Python Programming from Zero. About 11 minutes to read.
In short
A dict maps keys to values for instant lookup, which makes it ideal for counting and grouping. A set stores unique items and answers "is this in here?" quickly, plus union and intersection.
Think of it like this: A dict is a phone book: look up a name, get a number, without reading every page.
Explained simply
A dictionary, or dict, stores pairs: a key and its value, like {"apple": 3, "pear": 5}. You look things up by key instead of by position, just as you look up a word in a real dictionary to find its meaning.
Keys are unique. Assigning to a key that already exists replaces its value. Values can be anything, including lists or other dicts, but keys must be hashable, which in practice means unchangeable values such as strings, numbers or tuples.
Dicts are the main tool for counting and grouping. You walk through your data once, and for each item you update an entry in the dict: add one to a count, or append to a list for that group. This one pattern solves a huge number of everyday problems.
A set is a collection of unique items with no particular order: {"red", "blue"}. Adding something twice keeps one copy. Sets answer "have I seen this before?" very quickly and can compare groups: what is in both, in either, or in one but not the other.
Press Play on a diagram to walk through it one step at a time.
- 1ages["Ana"]
You ask for a key
- 2hash("Ana")
Key is turned into a number
- 3Jump to slot
The number points straight to a storage slot
- 4Confirm key
Check the stored key really equals "Ana"
- 5Return value
Missing key raises KeyError instead
- Returns the value
- Missing: raises KeyError
- Use when missing means a bug
- Returns value or default
- Never changes d
- Use for optional data
- Returns value or default
- Inserts the default if missing
- Use for grouping into lists
In depth
How hashing makes lookups fast
A dict is a hash table. To store a key, Python calls hash(key) to get a number, uses that number to pick a slot in an internal table, and stores the key and value there. To find it again, it does the same calculation and jumps to the same slot, then confirms with == that it is really the right key. If two keys land on the same slot (a collision), Python tries other slots in a fixed sequence. On average a lookup takes the same time whether the dict holds ten items or ten million.
Two rules follow. A key's hash must never change, so mutable lists and dicts cannot be keys. And equal values must hash the same, which is why 1, 1.0 and True count as the same key: d[1] = "a" then d[True] = "b" leaves one entry.
Since Python 3.7, dicts are guaranteed to keep keys in insertion order. Sets use the same kind of table, just without values.
- Checks items one by one
- Time grows with the size
- 1 million items: up to 1 million checks
- Works with any items
- Hash jumps near the right slot
- About the same time at any size
- 1 million items: a few checks
- Keys must be hashable
Reading and changing dicts safely
d[key] raises KeyError when the key is missing, which is right when a missing key means a bug. When it is normal for a key to be missing, use d.get(key, default), which returns the default and leaves d unchanged, or test first with key in d. d.setdefault(key, default) returns the existing value or inserts the default and returns it; that makes grouping a one-liner.
To remove entries, del d[key] raises KeyError if missing, while d.pop(key, None) does not. To merge, d.update(other) changes d in place, and since Python 3.9, a | b builds a new merged dict and a |= b updates a. In every merge, the right-hand side wins when both have the same key.
d.keys(), d.values() and d.items() return views: live windows onto the dict that reflect later changes. Two dicts are equal when they hold the same pairs, regardless of order.
- d.get("x") returns None if "x" is missing
- d.pop("x", None) removes "x" if present, no error
- defaults | user_settings: user settings win
Counting and grouping patterns
Counting: counts[x] = counts.get(x, 0) + 1 inside a loop. get() supplies 0 the first time a key appears. collections.Counter does the same in one call, and Counter(words).most_common(3) gives the top three with their counts.
Grouping: groups.setdefault(key, []).append(item). The first time a key appears, setdefault inserts an empty list; every time, it returns the list for that key, and append adds the item. collections.defaultdict(list) does this automatically: groups[key].append(item).
Two more recipes come up often. To sort a dict by value, sort its items: sorted(d.items(), key=lambda kv: kv[1], reverse=True). To find the key with the biggest value, max(d, key=d.get). To invert a dict, {v: k for k, v in d.items()} works, but if two keys share a value, only the last one survives.
- 1Take the next word
for w in words
- 2Compute its key
w[0], the first letter
- 3New key?
setdefault inserts an empty list
- 4Append the word
To the list for that key
- 5Result
A dict of lists, one per letter
Sets and set algebra
Create a set with braces, {1, 2, 3}, or from any iterable with set(items). An empty set must be set(), because {} is an empty dict. add(x) inserts, discard(x) removes without complaining, and remove(x) raises KeyError if x is missing.
The operators are where sets shine. a | b is the union (in either), a & b the intersection (in both), a - b the difference (in a but not b) and a ^ b the symmetric difference (in exactly one). a <= b asks whether a is a subset of b, and a.isdisjoint(b) whether they share nothing. The method forms, such as a.union(some_list), accept any iterable, not just sets.
Set items must be hashable, so you cannot put lists in a set. A frozenset is an immutable set that can itself be a dict key or an item of another set. Sets have no order, so print sorted(s) when you need stable output.
- a | b
- {1, 2, 3, 4}
- In either
- a & b
- {3}
- In both
- a - b
- {1, 2}
- Only in a
- b - a
- {4}
- Only in b
- a ^ b
- {1, 2, 4}
- In exactly one
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Create, read and update dicts~50m
- 2Iterate over keys, values and items~50m
- 3Count and group data with dicts~50m
- 4Use sets to remove duplicates~50m
- 5Apply set union and intersection~50m
Key points
- Use d.get(key, default) to avoid KeyError when a key might be missing.
- Loop with for key, value in d.items() to get both at once.
- Count with counts[x] = counts.get(x, 0) + 1.
- set(items) removes duplicates; | is union, & is intersection, - is difference.
- Dict keys and set items must be hashable, e.g. str, int or tuple.
Key terms
Tap a card to flip it. 0/5 known
Examples
words = "the cat and the hat and the bat".split()
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
print(counts["the"]) # 3
by_letter = {}
for w in words:
by_letter.setdefault(w[0], []).append(w)
print(by_letter["t"]) # ['the', 'the', 'the']
unique = set(words)
rhymes = {"cat", "hat", "mat"}
print(unique & rhymes) # {'cat', 'hat'}
print(len(unique)) # 5A word-frequency report
You want the two most common words in a sentence, ignoring case. Step 1: lower() and split() turn the text into a clean list of words. Step 2: the loop counts each word with get(), which supplies 0 the first time. Step 3: sorting the (word, count) pairs by count, biggest first, and slicing [:2] gives the top two. Step 4: Counter produces the same answer in one line; knowing both lets you understand Counter instead of treating it as magic.
from collections import Counter
text = "the cat and the hat and THE bat"
words = text.lower().split()
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
top = sorted(counts.items(), key=lambda kv: kv[1], reverse=True)[:2]
print(top) # [('the', 3), ('and', 2)]
print(Counter(words).most_common(2)) # [('the', 3), ('and', 2)]Comparing two guest lists
Two events had overlapping guests. Step 1: store each list as a set, which also drops any accidental duplicates. Step 2: & finds people who came both days. Step 3: | gives everyone, so its length is the number of unique guests. Step 4: - finds Monday-only guests and ^ those who came exactly once. Step 5: wrap results in sorted() so the output order is predictable; sets themselves have no order.
monday = {"ana", "bo", "cy", "di"}
tuesday = {"cy", "di", "ed"}
print(sorted(monday & tuesday)) # ['cy', 'di'] both days
print(len(monday | tuesday)) # 5 unique guests
print(sorted(monday - tuesday)) # ['ana', 'bo'] Monday only
print(sorted(monday ^ tuesday)) # ['ana', 'bo', 'ed'] exactly one day
print("ed" in tuesday) # True, a fast lookupQuick reference
- d.get(k, 0) returns 0 instead of raising KeyError; d.setdefault(k, []) also inserts it
- merged = defaults | overrides (Python 3.9+): the right side wins on duplicate keys
- Dicts keep insertion order, guaranteed since Python 3.7
- sorted(d.items(), key=lambda kv: kv[1], reverse=True) sorts by value, biggest first
- Counter(words).most_common(3) gives the 3 most frequent items with their counts
- set() is an empty set; {} is an empty dict
- s.discard(x) never fails; s.remove(x) raises KeyError if x is missing
- 1, 1.0 and True are the same dict key, because they are equal and hash the same
Common mistakes
- Reading d[key] for a key that may not exist; use get() or check with in.
- Expecting a set to keep insertion order or allow indexing.
- Writing {} for an empty set — that is an empty dict; use set().
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Given prices = {"apple": 0.5, "bread": 2.2, "milk": 1.1}, add cheese at 4.0, raise milk by 10%, remove bread, and print each item and price on its own line.
- Exercise 2medium
Group ["ana", "bo", "amy", "cy", "ben"] into a dict of lists by first letter, then print the groups in alphabetical order of the letter.
- Exercise 3hard
Write first_repeat(text) that returns the first character that appears a second time ("swiss" gives "s", "abc" gives None) and common(a, b) that returns the set of characters found in both strings. Both must run in linear time.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Are Python dictionaries ordered?
- Yes. Since Python 3.7, dicts officially keep keys in the order they were inserted. Sets do not keep any order.
- How do I sort a dictionary by value?
- Sort its items with a key: sorted(d.items(), key=lambda kv: kv[1]). Wrap the result in dict() if you want a dict back in that order.
- What is the difference between a set and a frozenset?
- A set can change with add() and remove(). A frozenset is immutable and hashable, so it can be a dict key or an item inside another set.
- How do I merge two dictionaries in Python?
- In Python 3.9 and later, a | b returns a new merged dict and a |= b updates a in place. On older versions, copy a and call update(b) on the copy.