如何在python中的字典列表中计算元素?

时间:2020-09-28 05:08:50

标签: python

假设我有这样的字典:

allName = {
          'name1': ['sainz', 'gasly'], 
          'name2': ['sainz', 'gasly', 'stroll'],
          'name3': ['sainz', 'gasly', 'stroll']
}

我怎么知道字典中有3个sainz名称,3个“ gasly”名称,2个“ stroll”名称?

我想这样打印出来:

sainz: 3
gasly: 3
stroll: 2

先谢谢!

3 个答案:

答案 0 :(得分:3)

最简单的方法可能是集合计数器加上itertools.chain

import itertools    
import collections
print(collections.Counter(itertools.chain(*data.values()))  

我认为会起作用

答案 1 :(得分:1)

使用collections.defaultdict

例如:

from collections import defaultdict

allName = {
          'name1': ['sainz', 'gasly'], 
          'name2': ['sainz', 'gasly', 'stroll'],
          'name3': ['sainz', 'gasly', 'stroll']
}

res = defaultdict(int)
for k, v in allName.items():
    for i in v:
        res[i]+=1
        
for k, v in res.items():
    print(f"{k}: {v}")     

输出:

sainz: 3
gasly: 3
stroll: 2

答案 2 :(得分:1)

另一种简单的方法是使用集合中的计数器

>>> from collections import Counter
>>> c = Counter()
>>> for names in allName.values():
...     for name in names:
...             c[name] += 1
...
>>> c
Counter({'sainz': 3, 'gasly': 3, 'stroll': 2})
>>>

说明
循环:遍历字典并找到列表中的所有项目。
count:然后将它们添加到计数器。