[英]Getting a specific key and value from a list of dictionaries
So I have this list of dictionaries:所以我有这个字典列表:
l = [{'COUNTRY': 'UK', 'STUDENT': 'JOHN'}, {'COUNTRY': 'PT', 'STUDENT':'PEDRO'}, {'COUNTRY': 'UK', 'STUDENT': 'KYLE'}, {'COUNTRY': 'IT', 'STUDENT':'PIRLO'}, {'COUNTRY': 'PT', 'STUDENT':'ANA'}, {'COUNTRY': 'FR', 'STUDENT':'VITO'}, {'COUNTRY': 'FR', 'STUDENT':'LOUIS'}]
I need to make a bar chart with the x axis being the countries that are on the list and and y axis being the number of times each country appears.我需要制作一个条形图,其中 x 轴是列表中的国家,y 轴是每个国家出现的次数。 My idea was to 'extract' those countries to a list, like this:
我的想法是将这些国家“提取”到一个列表中,如下所示:
country_list = ['UK','PT','UK','IT','PT','FR','FR']
Then I would have to count how many times does each country appears and sort the list by frequency.然后我必须计算每个国家出现了多少次,并按频率对列表进行排序。
After all that is done I would have two lists:完成所有这些后,我将有两个列表:
country = ['UK','PT','FR','IT']
frequency = [2,2,2,1]
With these two lists I would be able to make the bar chart.有了这两个列表,我就可以制作条形图了。 How can I get those two lists from the original list of dictionaries?
如何从原始字典列表中获取这两个列表?
Having your list有你的清单
l = [{'COUNTRY': 'UK', 'STUDENT': 'JOHN'}, {'COUNTRY': 'PT', 'STUDENT':'PEDRO'}, {'COUNTRY': 'UK', 'STUDENT': 'KYLE'}, {'COUNTRY': 'IT', 'STUDENT':'PIRLO'}, {'COUNTRY': 'PT', 'STUDENT':'ANA'}, {'COUNTRY': 'FR', 'STUDENT':'VITO'}, {'COUNTRY': 'FR', 'STUDENT':'LOUIS'}]
you could first extract all the values for the countries:您可以首先提取国家/地区的所有值:
In [18]: k = [i['COUNTRY'] for i in l]
Then you could use the Counter
from collections
module:然后你可以使用来自
collections
模块的Counter
:
In [19]: m = Counter(k)
Out[19]: Counter({'FR': 2, 'IT': 1, 'PT': 2, 'UK': 2})
To get the axes:获取坐标轴:
In [20]: countries = m.keys()
In [21]: frequency = m.values()
In [22]: countries
Out[22]: ['FR', 'PT', 'UK', 'IT']
In [23]: frequency
Out[23]: [2, 2, 2, 1]
l = [{'COUNTRY': 'UK', 'STUDENT': 'JOHN'}, {'COUNTRY': 'PT', 'STUDENT':'PEDRO'}, {'COUNTRY': 'UK', 'STUDENT': 'KYLE'}, {'COUNTRY': 'IT', 'STUDENT':'PIRLO'}, {'COUNTRY': 'PT', 'STUDENT':'ANA'}, {'COUNTRY': 'FR', 'STUDENT':'VITO'}, {'COUNTRY': 'FR', 'STUDENT':'LOUIS'}]
myDict = {}
for d in l:
c = d['COUNTRY']
myDict[c] = myDict.get(c,0)+1
print(myDict)
country = myDict.values()
frequency = myDict.keys()
print(country)
print(frequency)
=========
{'UK': 2, 'PT': 2, 'IT': 1, 'FR': 2}
dict_values([2, 2, 1, 2])
dict_keys(['UK', 'PT', 'IT', 'FR'])
#You can solve this problem easily by using lambda function:
country_list = list(map(lambda dict: dict['COUNTRY'], list))
# You can count the same data by using Counter function:
from collections import Counter
counter = Counter(country_list)
counter = ({'UK': 2, 'PT': 2, 'FR': 2, 'IT': 1})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.