Python · Dictionaries
Dictionaries for key-value lookups: get() with defaults, iterating items(), insertion order, and counting with Counter.
A dict maps keys to values. Looking up a key is fast (a hash table on average). Keys must be hashable, so ints, strings and tuples work but lists don’t.
Things I practised:
d[k]raisesKeyErrorifkis missing.d.get(k, default)returns the default instead.d.items(),d.keys()andd.values()give live views of the dict.- Since Python 3.7, dicts keep insertion order as a language guarantee.
d.setdefault(k, [])andcollections.defaultdictmake grouping easy.collections.Counteris a dict built for counting.d1 | d2merges two dicts (Python 3.9+).
from collections import Counter, defaultdict
marks = {"maths": 88, "physics": 79}
marks["python"] = 95
print(marks)
print(marks.get("chemistry", "n/a"))
for subject, m in marks.items():
print(f"{subject:>8}: {m}")
text = "to be or not to be"
print(Counter(text.split()).most_common(2))
by_len = defaultdict(list)
for w in text.split():
by_len[len(w)].append(w)
print(dict(by_len))
print({"a": 1} | {"b": 2})
Output:
{'maths': 88, 'physics': 79, 'python': 95}
n/a
maths: 88
physics: 79
python: 95
[('to', 2), ('be', 2)]
{2: ['to', 'be', 'or', 'to', 'be'], 3: ['not']}
{'a': 1, 'b': 2}Sources
- Data Structures: dictionaries — Python Software Foundation
- Mapping types: dict — Python Software Foundation
- collections.Counter — Python Software Foundation