Python 统计字典列表中某个值的出现次数

Python 统计字典列表中某个值的出现次数,python,list,dictionary,count,Python,List,Dictionary,Count,我不知道我是否通常会以这种方式存储信息,但它就是这样呈现给我的 假设我有一个字典列表,记录了UFO目击的细节,如下所示: aList = [{'country': 'japan', 'city': 'tokyo', 'year': 1995}, {'country': 'japan', 'city': 'hiroshima', 'year': 2005}, {'country': 'norway', 'city': 'oslo', 'year': 2005} ... etc] from col

我不知道我是否通常会以这种方式存储信息,但它就是这样呈现给我的

假设我有一个字典列表,记录了UFO目击的细节,如下所示:

aList = [{'country': 'japan', 'city': 'tokyo', 'year': 1995}, {'country': 'japan', 'city': 'hiroshima', 'year': 2005}, {'country': 'norway', 'city': 'oslo', 'year': 2005} ... etc]
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
我知道如何计算列表中出现的次数,但由于涉及到词典,我不知道该怎么做

例如,如果我想知道哪个国家的UFO目击次数最多,我该怎么做?

你可以使用和来计算每个国家在列表中出现的次数。之后,您可以使用
most_common
方法来获取显示最频繁的一个。代码如下所示:

aList = [{'country': 'japan', 'city': 'tokyo', 'year': 1995}, {'country': 'japan', 'city': 'hiroshima', 'year': 2005}, {'country': 'norway', 'city': 'oslo', 'year': 2005} ... etc]
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
下面是每个部分的功能演示:

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

以下是一个简明的版本:

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()
输出

[('japan', 2), ('norway', 1)]
[('oslo', 1), ('hiroshima', 1), ('tokyo', 1)]