Note keys(), values(), and items() return view objects that reflect changes to the dict in real time.
dict keysdict valuesiterate dictionaryloop over dict
Dictionary Comprehensions
syntax
{key_expr: val_expr for item in iterable if condition}
example
words = ["hello", "world", "python"]
lengths = {w: len(w) for w in words}
print(lengths)
original = {"a": 1, "b": 2, "c": 3}
filtered = {k: v for k, v in original.items() if v >= 2}
print(filtered)
from collections import defaultdict
dd = defaultdict(factory)
example
from collections import defaultdict
word_count = defaultdict(int)
for word in"the cat sat on the mat".split():
word_count[word] += 1print(dict(word_count))
output
{'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1}
Note defaultdict auto-creates missing keys using the factory function. Common factories: int (0), list ([]), set (set()).
defaultdictauto default valuecount occurrencesgroup by key