Sub topic 3
Dictionary Comprehensions and Practical Dictionary Patterns
Assume you know variables, loops, conditionals, f-strings, and mutable versus immutable objects. A dictionary maps hashable keys to values.
Dictionary comprehensions
A dictionary comprehension builds a dictionary from an iterable:
words = ["apple", "bob", "cat"]
lengths = {word: len(word) for word in words}
long_words = {word: len(word) for word in words if len(word) > 3}
print(lengths) # {'apple': 5, 'bob': 3, 'cat': 3}
print(long_words) # {'apple': 5}The expression before the colon produces each key and the expression after it produces each value.
Counting and grouping
Counter is a dictionary-like class for tallying values. defaultdict supplies a value automatically when a key is missing.
from collections import Counter, defaultdict
counts = Counter("banana")
print(counts) # Counter({'a': 3, 'n': 2, 'b': 1})
groups = defaultdict(list)
for word in ["apple", "avocado", "banana"]:
groups[word[0]].append(word)
print(dict(groups))
# {'a': ['apple', 'avocado'], 'b': ['banana']}For simple cases, setdefault(key, default) can create a missing value, but defaultdict is usually clearer for repeated grouping.
Sorting by key or value
sorted() returns a list. Sort dictionary items with a key function, then convert the result back to a dictionary if needed.
scores = {"ana": 90, "ben": 72, "cy": 85}
by_value = dict(sorted(scores.items(), key=lambda item: item[1], reverse=True))
by_name = dict(sorted(scores.items()))
print(by_value) # {'ana': 90, 'cy': 85, 'ben': 72}
print(by_name) # {'ana': 90, 'ben': 72, 'cy': 85}Nested dictionaries and copying
copy() makes a shallow copy. Nested mutable objects remain shared. deepcopy() recursively copies them.
import copy
original = {"settings": {"theme": "light"}}
shallow = original.copy()
shallow["settings"]["theme"] = "dark"
print(original["settings"]["theme"]) # dark
independent = copy.deepcopy(original)
independent["settings"]["theme"] = "blue"
print(original["settings"]["theme"]) # darkUse a deep copy when nested changes must not affect the original.
Changing a dictionary during iteration
Do not add or delete keys while directly iterating over a dictionary. Python raises RuntimeError because its size changes. Iterate over a list of keys instead:
data = {"a": 1, "b": 2, "c": 3}
for key in list(data):
if data[key] % 2:
del data[key]
print(data) # {'b': 2}Hash tables and lookup speed
A dictionary uses a hash table. Python hashes a key to choose where to search, so lookup, insertion, and deletion are usually constant-time, written as O(1). This depends on well-distributed hashes and is not a guarantee for every unusual case.
Keys must be hashable. Immutable values such as strings and tuples can usually be keys; lists cannot.
Exercise
Why does changing a nested list through a shallow dictionary copy also change the original?
Show answer
The shallow copy duplicates the outer dictionary but shares the same nested list. Use copy.deepcopy() to duplicate nested mutable objects.