L2·Control & Collections

🗺️Dictionaries

Hash-map key→value store. Ordered since 3.7.

dicthashgetitems

§ 1Access & default

d[k] raises KeyError. d.get(k, default) doesn't. d.setdefault(k, v) inserts if missing.

§ 2Iteration

for k in d, for v in d.values(), for k,v in d.items().

§ 3Comprehensions & merge

{k: v for k,v in pairs}. Python 3.9+: d1 | d2 merges.

Example

1ages = {"ada": 36, "bob": 42}
2ages["cai"] = 29
3print(ages.get("dee", -1))
4for k, v in ages.items():
5 print(k, v)

Try it live · Python runs in your browser

Loading playground…

Checkpoint quiz

Question 1 / 2
d.get('x') when 'x' missing returns:
Prev
Tuples
Next
Sets