簡體   English   中英

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

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

我有一個變量和從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}]

我只想要每個城市的“人口”價值。 從每個城市“人口”中列出價值的最有效或最簡單的方法是什么?

下面是我想出的代碼,但是效率很低。

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

我目前正在學習Python,任何建議都將對您有所幫助!

謝謝!

使用列表理解:

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

輸出

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

編輯

假設一個city沒有population

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

輸出 (列表中少數城市的人口遷移 ):

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

使用吸氣劑,這樣,如果其中一些未定義,則將具有空/無值。

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

如果您不想使用空值:

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