JimForTheWin
JimForTheWin

Reputation: 147

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.

Upvotes: 4

Views: 5684

Answers (1)

mgilson
mgilson

Reputation: 309929

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)

Upvotes: 8

Related Questions