Reputation: 368
I don't know if I would generally store information this way, but this is how it's been presented to me.
Say I have a list of dictionaries that records the details of let's say UFO sightings, and looks like this:
aList = [{'country': 'japan', 'city': 'tokyo', 'year': 1995}, {'country': 'japan', 'city': 'hiroshima', 'year': 2005}, {'country': 'norway', 'city': 'oslo', 'year': 2005} ... etc]
I know how to count the number of occurrences in a list, but with dictionaries involved, I'm not sure how I'd go about it.
If I wanted to know which country had the most sightings of UFOs for example, how could I do that?
Upvotes: 5
Views: 2950
Reputation:
You can use collections.Counter
and a generator expression to count how many times each country appears in the list. After that, you can use the most_common
method to get the one that appears the most. The code will look like this:
from collections import Counter
aList = [{'country': 'japan', 'city': 'tokyo', 'year': 1995}, {'country': 'japan', 'city': 'hiroshima', 'year': 2005}, {'country': 'norway', 'city': 'oslo', 'year': 2005}]
[(country, _)] = Counter(x['country'] for x in aList).most_common(1)
print(country)
# Output: japan
Below is a demonstration of what each part does:
>>> from collections import Counter
>>> aList = [{'country': 'japan', 'city': 'tokyo', 'year': '1995'}, {'country': 'japan', 'city': 'hiroshima', 'year': '2005'}, {'country': 'norway', 'city': 'oslo', 'year': '2005'}]
>>> # Get all of the country names
>>> [x['country'] for x in aList]
['japan', 'japan', 'norway']
>>> # Total the names
>>> Counter(x['country'] for x in aList)
Counter({'japan': 2, 'norway': 1})
>>> # Get the most common country
>>> Counter(x['country'] for x in aList).most_common(1)
[('japan', 2)]
>>> # Use iterable unpacking to extract the country name
>>> [(country, _)] = Counter(x['country'] for x in aList).most_common(1)
>>> print(country)
japan
>>>
Upvotes: 5
Reputation: 1822
Here's a concise version:
from collections import Counter
from operator import itemgetter
aList = [{'country': 'japan', 'city': 'tokyo', 'year': 1995}, {'country': 'japan', 'city': 'hiroshima', 'year': 2005}, {'country': 'norway', 'city': 'oslo', 'year': 2005}]
countries = Counter(map(itemgetter('country'), aList))
print countries.most_common()
cities = Counter(map(itemgetter('city'), aList))
print cities.most_common()
Output
[('japan', 2), ('norway', 1)]
[('oslo', 1), ('hiroshima', 1), ('tokyo', 1)]
Upvotes: 2