Skip to content

defaultdict(list) #7

Answered by goungoun
goungoun asked this question in Liner
Discussion options

You must be logged in to vote

https://docs.python.org/3/library/collections.html#collections.defaultdict

Using list as the default_factory, it is easy to group a sequence of key-value pairs into a dictionary of lists:

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
d = defaultdict(list)
for k, v in s:
    d[k].append(v)

sorted(d.items())
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

Setting the default_factory to int makes the defaultdict useful for counting (like a bag or multiset in other languages):

s = 'mississippi'
d = defaultdict(int)
for k in s:
    d[k] += 1

sorted(d.items())
[('i', 4), ('m', 1), ('p', 2), ('s', 4)]

Replies: 1 comment

Comment options

goungoun
Jul 27, 2024
Maintainer Author

You must be logged in to vote
0 replies
Answer selected by goungoun
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Liner
1 participant