Definition
Dictionary methods read and change key-value pairs. A dictionary comprehension builds a new dictionary from a loop, in one line.
In simple words
keys() gives the names, values() gives the numbers, and items() gives both. A comprehension is a short way of saying: for each item, make this key and this value.
Why it matters
Counting things, grouping data and swapping keys with values are everyday jobs, and these tools make them one-liners.
How it works
| Method | Does |
|---|---|
| get(k, default) | Safe read |
| keys(), values(), items() | Views of the contents |
| update(other) | Merges in another dict |
| pop(k) | Removes and returns a value |
| setdefault(k, v) | Reads, or sets when missing |
| d | other | Merged copy (Python 3.9+) |
In code
marks = {"Riya": 91, "Aman": 40, "Sara": 75}
passed = {name: m for name, m in marks.items() if m >= 50}
print(passed)
by_mark = {m: name for name, m in marks.items()}
print(by_mark[91])
counts = {}
for letter in "banana":
counts[letter] = counts.get(letter, 0) + 1
print(counts)
print(marks | {"Aman": 45, "Dev": 60})Output
{'Riya': 91, 'Sara': 75}
Riya
{'b': 1, 'a': 3, 'n': 2}
{'Riya': 91, 'Aman': 45, 'Sara': 75, 'Dev': 60}Common mistakes
- Changing a dict's size while looping over it, which raises an error. Loop over list(d.items()).
- Assuming values are unique when swapping keys and values. Duplicates are lost.
Check yourself
Summary
- get, items, update and pop cover most dict work.
- A comprehension builds a dict in one line.
Finished reading?
Sources: The Python Tutorial, python.org