从字典列表中获取特定键和值

时间:2017-05-23 09:57:13

标签: python python-2.7 list dictionary

所以我有这个词典列表:

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'}]

我需要制作一个条形图,其中x轴是列表中的国家,y轴是每个国家/地区出现的次数。我的想法是提取'列表中的那些国家,如下:

country_list = ['UK','PT','UK','IT','PT','FR','FR']

然后我必须计算每个国家出现的次数,并按频率对列表进行排序。

完成所有这些后,我会有两个列表:

country = ['UK','PT','FR','IT']

frequency = [2,2,2,1]

通过这两个列表,我可以制作条形图。如何从原始词典列表中获取这两个列表?

3 个答案:

答案 0 :(得分: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'])

答案 1 :(得分:0)

列出您的清单

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'}]

您可以先提取国家/地区的所有值:

In [18]: k = [i['COUNTRY'] for i in l]

然后您可以使用Counter模块中的collections

In [19]: m = Counter(k)
Out[19]: Counter({'FR': 2, 'IT': 1, 'PT': 2, 'UK': 2})

获取轴:

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]

答案 2 :(得分:0)

#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})