CollectionsChapter 39 of 114
Dictionary Methods
The full set of dict methods, and which ones change the dictionary.
The whole list
| Method | Does | Returns |
|---|---|---|
get(key, default) | look up without raising | the value or the default |
keys() | a live view of the keys | a view |
values() | a live view of the values | a view |
items() | key and value pairs | a view |
setdefault(key, default) | look up, creating it if missing | the value |
update(other) | copy pairs in | None |
pop(key, default) | remove and return | the value |
popitem() | remove and return the last pair | a tuple |
clear() | remove everything | None |
copy() | a new shallow copy | a dict |
fromkeys(keys, value) | build from keys | a dict |
Reading without raising
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:
scores = {"a": 1}
keys = scores.keys()
print(list(keys))
scores["b"] = 2
print(list(keys))Output
['a'] ['a', 'b']
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
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
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
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
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.
d = dict.fromkeys(["a", "b"], [])
d["a"].append(1)
print(d)Output
{'a': [1], 'b': [1]}Test yourself
2 questionsWhat 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.
Set Methods
Adding, removing, and the four ways to compare two sets.