Chapters
Python114 chapters

CollectionsChapter 39 of 114

Dictionary Methods

The full set of dict methods, and which ones change the dictionary.

The whole list

MethodDoesReturns
get(key, default)look up without raisingthe value or the default
keys()a live view of the keysa view
values()a live view of the valuesa view
items()key and value pairsa view
setdefault(key, default)look up, creating it if missingthe value
update(other)copy pairs inNone
pop(key, default)remove and returnthe value
popitem()remove and return the last paira tuple
clear()remove everythingNone
copy()a new shallow copya dict
fromkeys(keys, value)build from keysa dict

Reading without raising

Python
person = {"name": "Ada"}

print(person.get("name"))
print(person.get("age"))
print(person.get("age", "unknown"))
print("age" in person)

Output

Ada
None
unknown
False

Use [] when a missing key means a bug, and get() when absence is expected.

Views are live

keys(), values() and items() are windows onto the dictionary, not copies. Change it and they follow:

Python
scores = {"a": 1}
keys = scores.keys()

print(list(keys))
scores["b"] = 2
print(list(keys))

Output

['a']
['a', 'b']
Python
scores = {"a": 1, "b": 2}

for key in list(scores):
    if scores[key] < 2:
        del scores[key]

print(scores)

Output

{'b': 2}

setdefault builds nested structures

Python
groups = {}
for subject, name in [("maths", "ada"), ("maths", "grace"), ("code", "kat")]:
    groups.setdefault(subject, []).append(name)

print(groups)

Output

{'maths': ['ada', 'grace'], 'code': ['kat']}

It returns the existing list, or stores and returns a new one. No key check needed.

Merging

Python
defaults = {"colour": "black", "size": 10}
custom = {"size": 12}

print(defaults | custom)
print(defaults)

merged = dict(defaults)
merged.update(custom)
print(merged)

Output

{'colour': 'black', 'size': 12}
{'colour': 'black', 'size': 10}
{'colour': 'black', 'size': 12}

| builds a new dictionary; update() changes one in place. The right-hand side wins on a clash, which is what you want for overriding defaults.

Removing

Python
person = {"name": "Ada", "born": 1815, "tmp": True}

print(person.pop("tmp"))
print(person.pop("missing", "not there"))
print(person.popitem())
print(person)

Output

True
not there
('born', 1815)
{'name': 'Ada'}

popitem() takes the last inserted pair, which makes a dictionary usable as a stack of pairs.

fromkeys, and removing duplicates

Python
print(dict.fromkeys(["a", "b"], 0))
print(list(dict.fromkeys(["a", "b", "a", "c"])))

Output

{'a': 0, 'b': 0}
['a', 'b', 'c']

The second line is the idiomatic way to drop duplicates and keep the order, which a set cannot do.

Python
d = dict.fromkeys(["a", "b"], [])
d["a"].append(1)
print(d)

Output

{'a': [1], 'b': [1]}

Test yourself

2 questions

What does keys() give you?

Show the answer

A live view that reflects later changes — Because it is live, changing the dictionary while looping over it raises RuntimeError. Loop over list(d) instead.

What is wrong with dict.fromkeys(["a", "b"], [])?

Show the answer

Both keys share one list — fromkeys gives every key the same value object. It is the mutable-default trap in another costume.

Next chapter

Set Methods

Adding, removing, and the four ways to compare two sets.