Show contents
Chapter 2 of 7 · 20 min
Dictionaries and sets
By the end of this chapter, you'll be able to
- Explain why looking up a dictionary key is almost instant
- Compare the cost of a search in a list and in a dictionary
- Use a set to test membership and remove duplicates
- Count occurrences with a dictionary
Searching a list: one by one
To find out whether a number is in a list, Python compares the number with each item, from first to last. In the worst case, it makes as many comparisons as there are items: the search is O(n). With ten times more customers, it takes ten times longer.
customers = ["70 11 22 33", "76 44 55 66", "65 77 88 99"]
def search(items, number):
comparisons = 0
for c in items:
comparisons += 1
if c == number:
return True, comparisons
return False, comparisons
print(search(customers, "65 77 88 99"))
print(search(customers, "79 00 00 00"))
(True, 3)
(False, 3)
The dictionary: a hash table
A dictionary maps keys to values. Internally, it is a hash table: Python turns each key into a number, its hash, and that number points straight to the slot where the value is stored. To find a key again, it recomputes the hash and goes directly to the right slot, without looking at the others.
An analogy: in a library with no catalogue, you search every shelf. In a library where each book has a shelf mark, you walk straight to the right aisle. The hash is the shelf mark.
records = {
"70 11 22 33": {"name": "Awa Diallo", "city": "Bamako"},
"76 44 55 66": {"name": "Kofi Mensah", "city": "Accra"},
"65 77 88 99": {"name": "Lina Haddad", "city": "Tunis"},
}
print(records["76 44 55 66"]["name"])
print("79 00 00 00" in records)
print(records.get("79 00 00 00", "unknown"))
print(hash("70 11 22 33") == hash("70 11 22 33"))
Kofi Mensah
False
unknown
True
The same key always gives the same hash: that is what makes it findable. Reading, adding or deleting a key takes constant time on average, O(1), whatever the size of the dictionary.
The key is there: we return the value without having looked at any other record.
Text description of the animation
- We ask for the record that goes with this number.
- Python computes the key's hash. This computation does not depend on the number of records.
- The hash is turned into a position in the table: we go straight to that slot.
- The key is there: we return the value without having looked at any other record.
The set: keys without values
A set is a dictionary without values: it only keeps keys, with no duplicates and in no particular order. It is used for two things: testing very quickly whether an item is present, and removing duplicates.
sign_ups = ["Awa", "Kofi", "Awa", "Lina", "Kofi", "Tariq"]
unique = set(sign_ups)
print(len(sign_ups), "sign-ups,", len(unique), "people")
python = {"Awa", "Kofi", "Lina"}
web = {"Kofi", "Tariq"}
print("both courses:", sorted(python & web))
print("at least one:", sorted(python | web))
print("Python only:", sorted(python - web))
6 sign-ups, 4 people
both courses: ['Kofi']
at least one: ['Awa', 'Kofi', 'Lina', 'Tariq']
Python only: ['Awa', 'Lina']
& gives the intersection (in both), | the union (in at least one), - the difference. We sort with sorted before printing: a set has no guaranteed order.
Mini-lab: find a customerPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Worked exercise: best-selling products
A grocery records every sale in a list. Write count(sales) that returns a dictionary {product: number of sales}, then print the products from best-selling to least-selling.
sales = ["rice", "millet", "rice", "oil", "rice", "millet", "sugar"]
Hint 1
d.get(product, 0) + 1.Hint 2
sorted(counter.items(), key=lambda pair: pair[1], reverse=True).Show the solution and common mistakes
def count(sales):
counter = {}
for product in sales:
counter[product] = counter.get(product, 0) + 1
return counter
sales = ["rice", "millet", "rice", "oil", "rice", "millet", "sugar"]
counter = count(sales)
print(counter)
for product, n in sorted(counter.items(), key=lambda pair: pair[1], reverse=True):
print(product, n)
{'rice': 3, 'millet': 2, 'oil': 1, 'sugar': 1}
rice 3
millet 2
oil 1
sugar 1
The dictionary goes through the list only once: O(n). The standard library also offers collections.Counter(sales), which does the same in one line.
Common mistakes:
- Writing
counter[product] += 1with no starting value: the first time, the key does not exist and Python raisesKeyError. - Calling
sales.count(product)inside a loop oversales: eachcountgoes through the whole list again, and the total becomes O(n²).
Summary
- 1Searching a list compares the items one by one: O(n).
- 2A dictionary is a hash table: the key's hash leads straight to the value, in O(1) on average.
- 3A set keeps unique items and tests membership very fast; &, | and - give intersection, union and difference.
- 4Keys must be immutable: a tuple, yes; a list, no.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.