简体   繁体   中英

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.

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 :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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