Python Dictionaries · Lesson 53 of 149

Python Dictionary Methods

What you will learn

  • keys(), values() and items(), and what a view is
  • get and setdefault
  • update, in its different forms
  • pop, popitem, clear and copy
  • The merge operators | and |=
  • Why you must not change a dictionary while looping over it

1. Views: keys, values and items

Three methods give you views of the dictionary's contents:

d = {"a": 1, "b": 2, "c": 3}
print(d.keys())
print(d.values())
print(d.items())
dict_keys(['a', 'b', 'c'])
dict_values([1, 2, 3])
dict_items([('a', 1), ('b', 2), ('c', 3)])
Method Gives
d.keys() the keys
d.values() the values
d.items() (key, value) pairs (tuples)

A view is not a copy. It is a live window onto the dictionary, so it changes when the dictionary changes:

d = {"a": 1, "b": 2, "c": 3}
k = d.keys()
d["d"] = 4
print(k)
dict_keys(['a', 'b', 'c', 'd'])

You can loop over a view, use len, and test membership with in. A view cannot be indexed (d.keys()[0] is a TypeError: 'dict_keys' object is not subscriptable). Turn it into a list when you need a list:

print(list(d.keys()), list(d.items())[0])
print("a" in d.keys(), 2 in d.values(), ("a", 1) in d.items())
print(sum(d.values()), max(d.values()), min(d, key=d.get))
['a', 'b', 'c', 'd'] ('a', 1)
True True True
10 4 a

min(d, key=d.get) gives the key with the smallest value. (A plain for key in d also gives the keys, so d.keys() is rarely needed in a loop.)

Quick check: what does `list({"x": 1, "y": 2}.items())` give?

[('x', 1), ('y', 2)]: a list of pairs.

Views and sets

Key views (and item views) behave like sets, so you can combine them (sets are chapter 10):

d1 = {"a": 1, "b": 2}
d2 = {"b": 20, "c": 3}
print(sorted(d1.keys() & d2.keys()))
print(sorted(d1.keys() | d2.keys()))
print(sorted(d1.keys() - d2.keys()))
['b']
['a', 'b', 'c']
['a']
  • & gives the keys in both.
  • | gives the keys in either.
  • - gives the keys in the first but not the second.

2. get and setdefault

You know get from lesson 9.1: the value, or a default, and never an error.

setdefault(key, default) is a get that also stores: if the key exists, it returns the value; if not, it adds the key with the default and returns it:

d = {"a": 1}
print(d.setdefault("a", 99))
print(d.setdefault("b", 2))
print(d)
1
2
{'a': 1, 'b': 2}

"a" was already there, so its value stayed 1. "b" was new, so it was added. This is useful when each key holds a list you want to grow:

groups = {}
groups.setdefault("x", []).append(1)
groups.setdefault("x", []).append(2)
groups.setdefault("y", []).append(3)
print(groups)
{'x': [1, 2], 'y': [3]}

(collections.defaultdict does this more neatly, lesson 9.6.)

3. update: add and replace many pairs

update takes pairs from another dictionary, from keyword arguments, or from a list of pairs. For existing keys, the new value wins. It changes the dictionary in place and returns None:

d = {"a": 1}
result = d.update({"b": 2, "a": 10})
print(d, result)
d.update(c=3, d=4)
print(d)
d.update([("e", 5), ("f", 6)])
print(d)
d.update(zip("xy", [7, 8]))
print(d)
{'a': 10, 'b': 2} None
{'a': 10, 'b': 2, 'c': 3, 'd': 4}
{'a': 10, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}
{'a': 10, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'x': 7, 'y': 8}

Like the list methods (lesson 7.2), update returns None, so d = d.update(...) is a bug.

4. Removing items

Method What it does
d.pop(key) removes the key and returns its value; KeyError if missing
d.pop(key, default) the same, but returns default if missing
d.popitem() removes and returns the last pair added, as a tuple
d.clear() removes everything
del d[key] removes the key, with no return value
d = {"a": 1, "b": 2, "c": 3}
print(d.popitem())
print(d.popitem())
print(d)
('c', 3)
('b', 2)
{'a': 1}

popitem() takes pairs in last-in, first-out order, like a stack (lesson 7.6). On an empty dictionary it raises KeyError: 'popitem(): dictionary is empty'.

d = {"a": 1, "b": 2}
print(d.pop("a"))
print(d.pop("z", "default"))
d.pop("z")
1
default
KeyError: 'z'

5. copy

copy() makes a new dictionary with the same pairs. It is shallow: the values are shared (lesson 2.7):

d = {"a": 1, "b": 2}
c = d.copy()
c["new"] = 1
print(d)
print(c)

a = {"k": [1]}
b = a.copy()
b["k"].append(2)
print(a, b)
{'a': 1, 'b': 2}
{'a': 1, 'b': 2, 'new': 1}
{'k': [1, 2]} {'k': [1, 2]}

Adding a key to the copy did not affect the original, but changing a list inside it did, because both dictionaries hold the same list. copy.deepcopy(a) makes a fully independent copy (lesson 9.5).

6. Merging with | and |=

Python 3.9 and later can merge dictionaries with the | operator. It makes a new dictionary, and for a repeated key the right-hand value wins:

x = {"a": 1, "b": 2}
y = x | {"b": 20, "c": 3}
print(x)
print(y)
x |= {"z": 0}
print(x)
{'a': 1, 'b': 2}
{'a': 1, 'b': 20, 'c': 3}
{'a': 1, 'b': 2, 'z': 0}
  • x | other builds a new dictionary and leaves x alone.
  • x |= other updates x in place, like update.

For older versions, {**x, **other} does the same (lesson 8.3). | needs a dictionary on both sides, but |= also accepts a list of pairs.

7. Do not change a dictionary while looping over it

Adding or removing keys while looping over the dictionary raises an error:

d = {"a": 1, "b": 2}
for key in d:
    d["c"] = 3
RuntimeError: dictionary changed size during iteration

Loop over a copy of the keys instead, with list(d):

d = {"a": 1, "b": 2}
for key in list(d):
    if d[key] == 1:
        del d[key]
print(d)
{'b': 2}

Changing the value of an existing key during the loop is allowed. A neater approach is to build a new dictionary with a comprehension (lesson 9.3).

Worked example: updating stock

A shop has a stock list. A delivery arrives, one item sells out, and a new item is added.

stock = {"rice": 10, "salt": 4, "oil": 6}
delivery = {"rice": 5, "tea": 3}

for item, qty in delivery.items():
    stock[item] = stock.get(item, 0) + qty

sold_out = stock.pop("salt")
print(stock)
print("salt sold out with", sold_out, "left")
print(sorted(stock, key=stock.get, reverse=True))
{'rice': 15, 'oil': 6, 'tea': 3}
salt sold out with 4 left
['rice', 'oil', 'tea']
Step Method Effect
add the delivery get(item, 0) + qty rice becomes 15; tea is new, so it starts from 0
remove an item pop("salt") removes it and returns 4
rank by stock sorted(stock, key=stock.get, reverse=True) the keys, biggest stock first

The items and numbers are made up.

Common mistakes

  • Treating a view as a list. d.keys()[0] fails; use list(d.keys())[0].
  • Writing d = d.update(...). update returns None.
  • Changing the dictionary's size inside a for loop over it. Loop over list(d), or build a new dictionary.
  • Expecting copy() to copy nested lists. It is shallow.
  • Using pop on a missing key without a default.
  • Using | on Python older than 3.9.

Key takeaways

  • keys(), values() and items() give live views; convert them with list(...) to index them.
  • get reads safely; setdefault reads and stores a default if the key is new.
  • update adds and replaces pairs; d | other makes a merged copy and d |= other updates in place (Python 3.9+).
  • pop(key, default), popitem() (last pair), clear() and del remove items.
  • Never add or remove keys while looping over a dictionary; loop over list(d).

Practice

1. What do list({"a": 1, "b": 2}.values()) and list({"a": 1, "b": 2}.items()) give?

Show answer

[1, 2] and [('a', 1), ('b', 2)].

2. After d = {"a": 1}, what do d.setdefault("a", 5) and d.setdefault("b", 5) return?

Show answer

1 (the key a already exists, so its value is returned and kept) and 5 (the key b is new, so it is added with 5).

3. Merge {"x": 1} into d so that existing keys are replaced.

Show answer

d.update({"x": 1}) or d |= {"x": 1}.

4. Remove the key "tmp" from d without an error even if it is missing.

Show answer

d.pop("tmp", None).

5. Why does adding a key inside for key in d: raise a RuntimeError?

Show answer

The dictionary's size changed while Python was looping over it, which would make the loop unreliable. Loop over list(d) instead.

6. Is c = d.copy() enough to make c independent when the values are lists?

Show answer

No. The copy is shallow, so both dictionaries share the same lists. Use copy.deepcopy(d).