Skip to content

Python dictionary methods

Dicts map hashable keys to values and preserve insertion order (guaranteed since Python 3.7). Run any example.

18 entries

Reading

d = {"a": 1, "b": 2}
print(d["a"], d.get("z"), d.get("z", 0))

d[key] raises KeyError if missing; get() returns None or a default.

d = {"a": 1, "b": 2}
print(list(d.keys()), list(d.values()), list(d.items()))

keys(), values(), items() return live views.

d = {"a": 1}
print("a" in d, len(d))

Membership tests keys.

Changing

d = {"a": 1}
d.update({"b": 2}, c=3)
print(d)

update() from a dict and/or keyword args.

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

pop(key, default) removes and returns.

d = {"a": 1, "b": 2}
print(d.popitem(), d)

popitem() removes the last inserted pair.

d = {}
d.setdefault("tags", []).append("py")
print(d)

setdefault() inserts a default if missing and returns it.

d = {"a": 1}
del d["a"]
d.clear()
print(d)

del and clear().

Creating

print(dict.fromkeys(["x", "y"], 0))

fromkeys() (careful: a mutable default is shared).

print(dict(zip(["a", "b"], [1, 2])))

Build from two lists.

print({n: n * n for n in range(4)})

Dict comprehension.

d = {"a": [1]}
shallow = d.copy()
import copy
deep = copy.deepcopy(d)

copy() is shallow.

Merging & sorting

a, b = {"x": 1}, {"x": 2, "y": 3}
print(a | b, {**a, **b})

Merge (3.9+) or unpacking; right side wins.

scores = {"ann": 7, "bob": 9, "cy": 5}
print(dict(sorted(scores.items(), key=lambda kv: kv[1], reverse=True)))

Sort by value.

scores = {"ann": 7, "bob": 9}
print(max(scores, key=scores.get))

Key with the largest value.

for k, v in {"a": 1, "b": 2}.items():
    print(k, v)

Loop over pairs.

collections helpers

from collections import Counter
print(Counter("mississippi").most_common(2))

Counter counts hashable items.

from collections import defaultdict
groups = defaultdict(list)
for w in ["ant", "bee", "asp"]:
    groups[w[0]].append(w)
print(dict(groups))

defaultdict creates missing values automatically.

Frequently asked questions

How do I check if a key exists in a Python dict?

Use key in d. Avoid key in d.keys() (works, but longer) and never catch KeyError just to test membership.

Are Python dictionaries ordered?

Yes. Since Python 3.7 dicts preserve insertion order as part of the language specification.

get() vs setdefault()?

get() only reads and never changes the dict. setdefault() inserts the default value when the key is missing, then returns it.

Related cheat sheets