使用列表中的唯一键进行字典理解

dict comprehension with unique keys out of list

我不经常使用列表推导式,但我想知道下面几行是否可以是一行代码(是的,代码已经很小,但我很好奇):

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

数据将是:{'hi':1, 'hello':3, 'bob':2}

某事:

d = { ... 用于 lst 中的索引 } ????

我已经尝试了一些理解,但它们不起作用:

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

致谢

只需使用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