Dictionaries · 5 / 15 Theory

Common mistakes and good practices

These are the most frequent mistakes when working with dictionaries and how to avoid them.

KeyError: the key does not exist

It is the most common error. You have three ways to avoid it, depending on what you need:

prices = {"coffee": 1.5, "tea": 1.2}

# 1. Check first with in
if "juice" in prices:
    print(prices["juice"])
else:
    print("No juice")

# 2. get with a default value
print(prices.get("juice", 0))  # 0

# 3. try/except
try:
    print(prices["juice"])
except KeyError:
    print("No juice")

in looks for keys, not values

prices = {"coffee": 1.5, "tea": 1.2}
print("coffee" in prices)  # True
print(1.5 in prices)       # False
print(1.5 in prices.values())  # True

Duplicate keys: the last one wins

d = {"a": 1, "a": 2}
print(d)  # {'a': 2}

book = {}
book["ana"] = "600111222"
book["ana"] = "611999888"   # overwrites, does not add
print(book)  # {'ana': '611999888'}

Keys must be immutable

Text, numbers and tuples can be keys. Lists and other dictionaries cannot:

d = {}
d[(1, 2)] = "point"   # correct: a tuple
d[[1, 2]] = "point"   # TypeError: unhashable type: 'list'

Numeric keys and text keys are not the same

d = {1: "one", "1": "text one"}
print(d[1])    # one
print(d["1"])  # text one

This mistake shows up when reading data with input(), which always returns text: if the dictionary keys are numbers, convert first with int().

Empty dictionary and empty set

{} creates a dictionary. For an empty set use set().

Good practices

  • Use clear and consistent key names: "name", "age"; do not mix "Name" and "name".
  • Put in the key what you are going to look up. If you search by name, the name must be the key.
  • To count or group, use get or setdefault instead of checking with an if.
  • Do not modify a dictionary while looping over it.
  • To show the contents in order, loop over sorted(d); do not rely on the order being what you expect if the data comes from elsewhere.

When to use a dictionary

You need…Use
An ordered collection of elementslist
A fixed record that does not changetuple
Unique values, without repeatsset
To look up one piece of data from another (name → phone, word → times)dictionary

If you have got this far you already know the four basic data structures of Python. Review Coffee shop and Student records to check it.