简体   繁体   English

python中有什么方法可以从字典列表中获取特定的值列表?

[英]Is there any way in python to get a specific list of value from list of dict?

I have a variable and list imported from excel that looks like below: 我有一个变量和从excel导入的列表,如下所示:

cities= [{'City': 'Buenos Aires',
  'Country': 'Argentina',
  'Population': 2891000,
  'Area': 4758},
 {'City': 'Toronto',
  'Country': 'Canada',
  'Population': 2800000,
  'Area': 2731571},
 {'City': 'Pyeongchang',
  'Country': 'South Korea',
  'Population': 2581000,
  'Area': 3194},
 {'City': 'Marakesh', 'Country': 'Morocco', 'Population': 928850, 'Area': 200},
 {'City': 'Albuquerque',
  'Country': 'New Mexico',
  'Population': 559277,
  'Area': 491},
 {'City': 'Los Cabos',
  'Country': 'Mexico',
  'Population': 287651,
  'Area': 3750},
 {'City': 'Greenville', 'Country': 'USA', 'Population': 84554, 'Area': 68},
 {'City': 'Archipelago Sea',
  'Country': 'Finland',
  'Population': 60000,
  'Area': 8300},
 {'City': 'Walla Walla Valley',
  'Country': 'USA',
  'Population': 32237,
  'Area': 33},
 {'City': 'Salina Island', 'Country': 'Italy', 'Population': 4000, 'Area': 27},
 {'City': 'Solta', 'Country': 'Croatia', 'Population': 1700, 'Area': 59},
 {'City': 'Iguazu Falls',
  'Country': 'Argentina',
  'Population': 0,
  'Area': 672}]

I just want the value 'Population' from each cities. 我只想要每个城市的“人口”价值。 What is the most efficient or easiest way to make a list with value from each cities 'Population'? 从每个城市“人口”中列出价值的最有效或最简单的方法是什么?

Below is the code that I came up with, but it's inefficient. 下面是我想出的代码,但是效率很低。

City_Population = [cities[0]['Population'], cities[1]['Population'], cities[2]['Population']]

I am currently learning Python and any advice would be helpful! 我目前正在学习Python,任何建议都将对您有所帮助!

Thank you! 谢谢!

Using list comprehension: 使用列表理解:

print([city['Population'] for city in cities])

OUTPUT : 输出

[2891000, 2800000, 2581000, 928850, 559277, 287651, 84554, 60000, 32237, 4000, 1700, 0]

EDIT : 编辑

Assuming there is no population in a city : 假设一个city没有population

print([city['Population'] for city in cities if 'Population' in city])

OUTPUT (removed population from a few cities in the list): 输出 (列表中少数城市的人口迁移 ):

[2891000, 2800000, 2581000, 928850, 287651, 84554, 32237, 4000]

Use a getter, that way you will have empty/none values if some of them are not defined. 使用吸气剂,这样,如果其中一些未定义,则将具有空/无值。

populations = [city.get('Population') for city in cities]

If you don't want the empty values: 如果您不想使用空值:

populations = [pop for pop in populations if pop is not None]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM