简体   繁体   English

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

[英]Return count of unique values from list of dictionaries

I have a list of dictionaries: 我有一个字典列表:

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'}]

I need to obtain the value, and count of the unique values. 我需要获取值,并计算唯一值。

Example output needs to be: 输出示例如下:

prod2261.example.com, 2
prod2261.example.com, 5
....etc....

So far I can get a set of all unique values: 到目前为止,我可以获得一组所有唯一值:

unique_values = set(e['device'] for e in event_results)

But I'm struggling to iterate over both lists and return just a count for each item in the unique_values set without creating a bunch of temporary lists and such to store values in and then len() at the end. 但是我一直在努力遍历两个列表,并只返回unique_values集中每个项目的计数,而没有创建一堆临时列表,并且先将值存储在len()中。

I think the solution is something to do with list comprehension, but I just can't get my head around it. 我认为解决方案与列表理解有关,但是我只是无法解决。

just use a collections.Counter instead of a set and you're done :) 只需使用collections.Counter而不是set :)

import collections
unique_counts = collections.Counter(e['device'] for e in event_results)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM