Python Dictionaries · Lesson 52 of 149

Python Dictionaries

What you will learn

  • What a dictionary is: keys that point to values
  • The ways to create one
  • Reading with [] and get, and the KeyError
  • Adding, changing and deleting items
  • The rules for keys and values
  • in, len, truthiness and equality

1. What is a dictionary?

A dictionary (type dict) stores pairs: a key and the value it stands for. You look things up by key, like looking up a word in a real dictionary, or a name in a phone book. You write it with curly brackets, each pair as key: value:

person = {"name": "Rina", "age": 25, "city": "Dhaka"}
print(person)
print(person["name"])
print(type(person), len(person))
{'name': 'Rina', 'age': 25, 'city': 'Dhaka'}
Rina
<class 'dict'> 3

A list finds an item by its position (lst[0]). A dictionary finds a value by its key (person["name"]), which is far clearer when the data has names, such as a record, a settings table, or counts.

Quick check: what does `{"a": 1, "b": 2}["b"]` give?

2. The key "b" points to the value 2.

2. Creating dictionaries

empty = {}
print(empty, type(empty), len(empty))
print(dict())
print(dict(a=1, b=2))
print(dict([("x", 1), ("y", 2)]))
print(dict(zip("ab", [1, 2])))
print(dict.fromkeys(["a", "b"], 0))
{} <class 'dict'> 0
{}
{'a': 1, 'b': 2}
{'x': 1, 'y': 2}
{'a': 1, 'b': 2}
{'a': 0, 'b': 0}
Way Meaning
{} the empty dictionary (not an empty set)
dict(a=1, b=2) keyword form: the keys become text names, and must be valid names
dict(list_of_pairs) from a list of (key, value) pairs
dict(zip(keys, values)) from two lists (lesson 6.6)
dict.fromkeys(keys, value) the same value for every key (None if you leave it out)

{} makes an empty dictionary. For an empty set, you must write set() (chapter 10).

A trap with fromkeys

If the common value is mutable, all the keys share it:

d = dict.fromkeys(["a", "b"], [])
d["a"].append(1)
print(d)
{'a': [1], 'b': [1]}

Both keys point to one list (lesson 2.7). Build the dictionary with a comprehension instead, to give each key its own list:

d2 = {k: [] for k in ["a", "b"]}
d2["a"].append(1)
print(d2)
{'a': [1], 'b': []}

3. Reading values

Use the key in square brackets, or the method get:

person = {"name": "Rina", "age": 25, "city": "Dhaka"}
print(person["age"])
print(person.get("city"))
print(person.get("zip"))
print(person.get("zip", "none"))
25
Dhaka
None
none
  • person["age"] gives the value, but a missing key is an error.
  • person.get("zip") returns None for a missing key, with no error.
  • person.get("zip", "none") returns your default instead.
person["zip"]
KeyError: 'zip'

A KeyError is the dictionary's version of the list's IndexError. Use [] when the key must exist (so a mistake shows up at once), and get when a missing key is normal.

Keys are case-sensitive and must match exactly: person.get("Name") is None.

4. Testing for a key

in and not in test the keys (not the values):

print("name" in person, "zip" in person)
print("Rina" in person)
print("zip" not in person)
True False
False
True

"Rina" in person is False, because "Rina" is a value, not a key. Looking for a key is fast, however big the dictionary is (lesson 9.7).

5. Adding, changing and deleting

Assigning to a key adds the pair if the key is new, and changes it if the key exists:

person["age"] = 26
person["email"] = "r@example.com"
print(person)
{'name': 'Rina', 'age': 26, 'city': 'Dhaka', 'email': 'r@example.com'}

Deleting uses del or pop:

del person["email"]
print(person)
print(person.pop("city"))
print(person)
print(person.pop("zzz", None))
{'name': 'Rina', 'age': 26, 'city': 'Dhaka'}
Dhaka
{'name': 'Rina', 'age': 26}
None
  • del d[key] removes the pair and raises KeyError if the key is missing.
  • d.pop(key) removes it and returns the value; give a second argument as a default to avoid the error, as in pop("zzz", None).

You can also update a value with the key's current value. Reading a missing key first is an error, so use get:

inventory = {"apples": 3}
inventory["apples"] += 2
inventory["pears"] = inventory.get("pears", 0) + 1
print(inventory)
{'apples': 5, 'pears': 1}

inventory["plums"] += 1 would raise KeyError: 'plums', because += must first read the old value.

6. Rules for keys and values

Values can be anything: numbers, text, lists, other dictionaries, None, even functions:

mixed = {"list": [1, 2], "dict": {"k": "v"}, "none": None, "func": len}
print(mixed["list"][0], mixed["dict"]["k"], mixed["func"]("abc"))
1 v 3

Keys are stricter:

  1. A key must be unique. A repeated key keeps only the last value.
  2. A key must be hashable: in practice, immutable (numbers, text, tuples of those, None, True/False). Lists, sets and dictionaries cannot be keys.
d = {"a": 1, "a": 2, "b": 3}
print(d, len(d))
{'a': 2, 'b': 3} 2
{[1]: 1}
TypeError: unhashable type: 'list'

Keys that are equal count as the same key, even across types: 1, 1.0 and True are equal, so they collapse into one:

print({1: "int", 1.0: "float", True: "bool"})
{1: 'bool'}

The key stayed 1 (the first one), and the value became the last, "bool". Lesson 9.7 explains hashing.

7. Length, truth and equality

d = {"x": 1, "y": 2, "z": 3}
print(len(d))
print(bool({}), bool({"a": 0}))
print({"a": 1, "b": 2} == {"b": 2, "a": 1})
3
False True
True
  • len counts the pairs.
  • An empty dictionary is false; any other is true, even {"a": 0} (lesson 5.3).
  • Two dictionaries are equal when they have the same pairs. The order does not matter for ==.

Like lists, a dictionary is mutable, so b = a gives one dictionary two names (lesson 2.7):

a = {"k": 1}
c = a
c["new"] = True
print(a)
{'k': 1, 'new': True}

Worked example: a shopping bill

A shop has prices in a dictionary. A cart holds items and quantities. Find the total, and treat an unknown item as costing 0.

prices = {"apples": 0.5, "bread": 2.0, "milk": 1.2}
cart = {"apples": 4, "bread": 1, "tea": 2}

total = 0
for item, qty in cart.items():
    price = prices.get(item, 0)
    total += price * qty
print(total)
print("tea" in prices, "milk" in prices)
4.0
False True
Item Price Quantity Cost
apples 0.5 4 2.0
bread 2.0 1 2.0
tea not found: get gives 0 2 0

The total is 2.0 + 2.0 + 0. cart.items() gives each key and value (lesson 9.3). The prices are made up.

Common mistakes

  • Using [] for a key that may be missing, and getting a KeyError. Use get.
  • Looking for a value with in. in tests keys only.
  • Writing {} for an empty set. It is an empty dictionary.
  • Using a list as a key. Use a tuple.
  • Forgetting that a repeated key keeps only the last value.
  • Using dict.fromkeys(keys, []) and sharing one list.

Key takeaways

  • A dictionary maps unique, hashable keys to values of any type, written {key: value}.
  • Read with d[key] (error if missing) or d.get(key, default) (safe).
  • Assigning to a key adds or changes a pair; del d[key] and d.pop(key) remove one.
  • key in d tests keys; len(d) counts pairs; an empty dictionary is false; == ignores order.
  • Dictionaries are mutable: a second name is not a copy.

Practice

1. Make a dictionary with "title": "Python" and "pages": 300, and read the pages.

Show answer
book = {"title": "Python", "pages": 300}
print(book["pages"])

2. What does {"a": 1}.get("b", 0) give?

Show answer

0, the default, because the key "b" is missing.

3. What does "Rina" in {"name": "Rina"} give, and why?

Show answer

False. in tests the keys, and "Rina" is a value.

4. What happens to {"x": 1, "x": 2}?

Show answer

Keys must be unique, so only the last value is kept: the dictionary is {'x': 2}.

5. Add 1 to the count of "a" in counts, even if "a" is not yet there.

Show answer

counts["a"] = counts.get("a", 0) + 1.

6. Why is {[1, 2]: "x"} an error?

Show answer

A list is mutable and not hashable, so it cannot be a key. Use a tuple, {(1, 2): "x"}.