The collections module offers specialized data structures. The two most useful ones solve perfectly the counting and grouping patterns you learned with dictionaries.
Counter: counting effortlessly
Counter takes any collection and returns a dictionary with the number of times each element appears:
from collections import Counter
count = Counter("abracadabra")
print(count) # Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
print(count["a"]) # 5
print(count["z"]) # 0 (no KeyError)
words = "the sun and the sea".split()
print(Counter(words)) # Counter({'the': 2, 'sun': 1, 'and': 1, 'sea': 1})
It is a normal dictionary with some extras, so you can loop over it with items(), use len() or sorted().
most_common: the most frequent
count = Counter("abracadabra")
print(count.most_common(2)) # [('a', 5), ('b', 2)]
print(count.most_common(1)) # [('a', 5)]
for letter, times in count.most_common(3):
print(letter, times)
# a 5
# b 2
# r 2
When there is a tie, most_common keeps the order in which the elements first appeared.
defaultdict: default values
A defaultdict automatically creates the value of a key that does not exist, using the function you give it. With list you group without checking anything:
from collections import defaultdict
groups = defaultdict(list)
for word in ["sun", "sea", "sky", "moon", "star"]:
groups[len(word)].append(word)
print(dict(groups))
# {3: ['sun', 'sea', 'sky'], 4: ['moon', 'star']}
With int you count (the default value of int() is 0):
count = defaultdict(int)
for letter in "hola":
count[letter] += 1
print(dict(count)) # {'h': 1, 'o': 1, 'l': 1, 'a': 1}
Comparing with normal dictionaries
| Task | Normal dictionary | With collections |
|---|---|---|
| Counting | d[x] = d.get(x, 0) + 1 | Counter(data) |
| Grouping into lists | if k not in d: d[k] = [] | defaultdict(list) |
| The most frequent | sort by hand | .most_common(n) |
Other useful structures
deque: a queue with fast insertion and removal at both ends (append,appendleft,pop,popleft).namedtuple: a tuple with names for its fields, likePoint(x=3, y=4).
from collections import deque, namedtuple
queue = deque([1, 2, 3])
queue.append(4)
print(queue.popleft()) # 1
print(list(queue)) # [2, 3, 4]
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y) # 3 4
Practice in Most common words and Cities by country.