Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从字典列表返回唯一值的计数_Python_List_Dictionary_List Comprehension - Fatal编程技术网

Python 从字典列表返回唯一值的计数

Python 从字典列表返回唯一值的计数,python,list,dictionary,list-comprehension,Python,List,Dictionary,List Comprehension,我有一份字典清单: event_results = [{'device': 'prod2261.example.com'}, {'device': 'npbodb253.example.com'}, {'device': 'db221.example.com'}, {'device': 'db219.example.com'}, {'device': 'db209.example.com'}, {'device': 'db243.example.com'}, {'device': 'prod27

我有一份字典清单:

event_results = [{'device': 'prod2261.example.com'}, {'device': 'npbodb253.example.com'}, {'device': 'db221.example.com'}, {'device': 'db219.example.com'}, {'device': 'db209.example.com'}, {'device': 'db243.example.com'}, {'device': 'prod277.example.com'}, {'device': 'prod2228.example.com'}, {'device': 'prod2252.example.com'}, {'device': 'prod2116.example.com'}, {'device': 'prod224.example.com'}, {'device': 'db223.example.com'}, {'device': 'db229.example.com'}, {'device': 'prod2116.example.com'}, {'device': 'db221.example.com'}, {'device': 'db239.example.com'}, {'device': 'npbodb249.example.com'}, {'device': 'db210.example.com'}, {'device': 'db219.example.com'}, {'device': 'db243.example.com'}, {'device': 'prod2210.example.com'}, {'device': 'prod224.example.com'}, {'device': 'npbodb253.example.com'}, {'device': 'npbovwa018.example.com'}, {'device': 'npbovwa018.example.com'}, {'device': 'db221.example.com'}, {'device': 'db243.example.com'}, {'device': 'prod2228.example.com'}]
我需要获得值,以及唯一值的计数

示例输出需要是:

prod2261.example.com, 2
prod2261.example.com, 5
....etc....
到目前为止,我可以得到一组所有唯一的值:

unique_values = set(e['device'] for e in event_results)
但是我正在努力迭代这两个列表,只返回unique_值集中每个项目的计数,而不创建一组临时列表,这样可以在其中存储值,然后在最后返回len()


我认为解决方案与列表理解有关,但我就是想不起来。

只需使用
集合。计数器
而不是
集合
就可以了:)


哇,你说得对!即使在设置中使用itemgetter运行
timeit
,这也比字典查找慢得多(11s vs 8s)。我被彻底纠正了
import collections
unique_counts = collections.Counter(e['device'] for e in event_results)