FotisK
FotisK

Reputation: 1177

dict comprehension with unique keys out of list

i have used list comprehensions not very often but i was wondering if the below lines can be a one liner (yes the code is already small, but i am curious):

lst = ['hi', 'hello', 'bob', 'hello', 'bob', 'hello']
for index in lst:
    data[index] = data.get(index,0) + 1

data would be: {'hi':1, 'hello':3, 'bob':2}

something:

d = { ... for index in lst } ????

I have tried some comprehensions but they don't work:

d = { index:key for index in lst if index in d: key = key + 1 else key = 1 }

Thanks in adv.

Upvotes: 0

Views: 307

Answers (1)

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23223

Simply use collections.Counter

A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

import collections
l = ['hi', 'hello', 'bob', 'hello', 'bob', 'hello']
c = collections.Counter(l)
assert c['hello'] == 3

Upvotes: 3

Related Questions