Learn/Python/13. Dictionaries and sets in depth
Lesson 13 of 15
Sign in

Python, lesson 13

Dictionaries and sets in depth

Dictionaries and sets are built on the same idea: a hash table that finds an item by its value in roughly constant time, no matter how many items there are. That makes them the go-to tools for three everyday jobs: counting things, grouping things and comparing groups.

Counting

The hand-written way to count uses get() with a default of 0:

Counting is so common that the collections module has a dictionary built for it, Counter. Hand it any iterable and it counts the items. A missing key reads as 0 instead of raising KeyError:

most_common() sorts by count; items with equal counts stay in the order they were first seen. If you need a different tie-break, sort votes.items() yourself with a key.

2 exercises to try what you just read.

Exercise 1

Most used words

Press Ctrl Enter or Check to test your code.

Exercise 2

Club overlap

Press Ctrl Enter or Check to test your code.

Grouping

To group items, you need "a list per key". setdefault() creates the list the first time a key appears:

defaultdict does the same with less noise. You give it a function that builds the default value, and it calls it whenever you read a missing key with square brackets:

defaultdict(int) counts just like Counter, because int() returns 0. Note that only d[key] creates defaults; d.get(key) still returns None for a missing key.

Useful dictionary methods

  • d.keys(), d.values(), d.items() give live views of the contents.
  • d.pop(key, default) removes a key and returns its value.
  • d | other builds a new merged dictionary; on clashes, the right side wins.
  • {k: v for k, v in d.items() if v > 1} builds a filtered copy (a dict comprehension).

Sets

A set is an unordered collection with no duplicates. It's the quickest way to remove repeats, and x in some_set is fast even for huge sets.

Sets support the operations you know from maths, as operators or methods:

OperatorMethodResult
a | ba.union(b)in either
a & ba.intersection(b)in both
a - ba.difference(b)in a but not b
a ^ ba.symmetric_difference(b)in exactly one
a <= ba.issubset(b)every item of a is in b

Because sets have no order, use sorted() when you print one so the output is predictable.

Set items and dictionary keys must be hashable: strings, numbers and tuples are fine; lists and other sets are not. Use a frozenset if you need a set inside a set.

Further reading

  • The Python Tutorial: Sets and dictionaries
  • collections.Counter and defaultdict
  • Set types

Read all of the input text. Make it lowercase, split it on whitespace, and strip the punctuation characters .,!?;: from both ends of each word (skip any word that becomes empty). Print the three most frequent words as word count, most frequent first. Break ties alphabetically. If there are fewer than three distinct words, print them all.

Sample input:

Sample output:

The chess club and the drama club each send in a list of members. The first input line holds the chess members, the second line holds the drama members, separated by spaces. Either line may be empty, and a name may be repeated by mistake.

Print three lines, each listing names in alphabetical order separated by single spaces (a label with nothing after it if the group is empty):

Sample input:

Sample output:

counts = {}
for fruit in ["apple", "pear", "apple"]:
    counts[fruit] = counts.get(fruit, 0) + 1
# {'apple': 2, 'pear': 1}
from collections import Counter

votes = Counter(["red", "blue", "red", "green", "red"])
print(votes["red"])          # 3
print(votes["purple"])       # 0
print(votes.most_common(2))  # [('red', 3), ('blue', 1)]
votes.update(["blue", "blue"])  # add more counts
print(votes.total())         # 7
groups = {}
for word in ["ant", "bee", "asp", "cat"]:
    groups.setdefault(word[0], []).append(word)
# {'a': ['ant', 'asp'], 'b': ['bee'], 'c': ['cat']}
from collections import defaultdict

by_length = defaultdict(list)
for word in ["ant", "bee", "wasp", "moth"]:
    by_length[len(word)].append(word)
# defaultdict(<class 'list'>, {3: ['ant', 'bee'], 4: ['wasp', 'moth']})
seen = set()             # {} would be an empty *dict*
seen.add("ana")
seen.add("ana")          # no effect: already there
unique = set([3, 1, 3, 2])   # {1, 2, 3}
The cat sat. The dog sat!
The end?
the 3
sat 2
cat 1
both: <in both clubs>
chess only: <only in chess>
drama only: <only in drama>
ana ben cleo ben
cleo dev ana
both: ana cleo
chess only: ben
drama only: dev