devnotes.

Dictionary and Set Comprehensions

Dict and set comprehensions extend the list-comprehension syntax to two more built-in collection types, and collections provides specialized dict variants worth knowing.

words = ["apple", "banana", "cherry", "date"]

lengths = {word: len(word) for word in words}          # dict comprehension
first_letters = {word[0] for word in words}              # set comprehension
swapped = {v: k for k, v in lengths.items()}               # invert a dict

from collections import defaultdict, Counter

word_counts = Counter("mississippi")            # Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})
print(word_counts.most_common(2))                 # [('i', 4), ('s', 4)]

groups = defaultdict(list)                          # never raises KeyError — auto-creates a default
for word in words:
    groups[word[0]].append(word)                     # no need to check if the key exists first

Dict comprehensions ({key_expr: value_expr for item in iterable}) and set comprehensions ({expr for item in iterable}) follow exactly the pattern established by list comprehensions, and support the same if filtering and multiple for clauses.

collections.Counter is purpose-built for counting hashable items — it behaves like a dict mapping each distinct item to its count, and adds convenience methods like .most_common(n) for quickly finding the most frequent elements, saving the manual loop-and-increment pattern that counting would otherwise require.

collections.defaultdict(list) (or defaultdict(int), etc.) eliminates the common "check if key exists, initialize if not, then update" pattern — accessing a missing key automatically creates it with a default value (an empty list, 0, and so on) produced by the factory function passed in, rather than raising a KeyError.

Dictionary and Set Comprehensions in Python | DevNotes