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

时间:2014-05-20 16:49:27

标签: 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': '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_values集中每个项目的计数,而不创建一堆临时列表,例如存储值,然后在最后存储len()。

我认为解决方案与列表理解有关,但我无法理解它。

1 个答案:

答案 0 :(得分:4)

只需使用collections.Counter代替set即可完成:)

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