簡體   English   中英

Python字典理解以獲取字典列表

[英]Python Dictionary comprehension for a list of dictionaries

我想從以下列表創建字典

[{'fips': '01001', 'state': 'AL', 'name': 'Autauga County'}, {'fips': '20005', 'state': 'KS', 'name': 'Atchison County'}, {'fips': '47145', 'state': 'TN', 'name': 'Roane County'}]

結果應以名稱為鍵,以“美國”為值。

例如:

{'Autauga County': 'United States', 'Atchison County' : 'United States',  'Roane County' : 'United States'}

我可以通過幾個for循環來做到這一點,但是我想學習如何使用Dictionary Comprehensions。

in_list = [{'fips': '01001', 'state': 'AL', 'name': 'Autauga County'}, 
           {'fips': '20005', 'state': 'KS', 'name': 'Atchison County'},
           {'fips': '47145', 'state': 'TN', 'name': 'Roane County'}]

out_dict = {x['name']: 'United States' for x in in_list if 'name' in x}

一些學習注意事項:

  • 理解僅適用於Python 2.7及更高版本
  • 字典理解與列表理解非常相似,但大括號{} (和鍵)除外
  • 如果您不知道,您還可以在for循環后添加一個更復雜的控制流,例如[x for x in some_list if (cond)]

為了完整起見,如果您不能使用理解力,請嘗試以下方法

out_dict = {}

for dict_item in in_list:
    if not isinstance(dict_item, dict):
        continue

    if 'name' in dict_item:
        in_name = dict_item['name']
        out_dict[in_name] = 'United States'

如評論中所述,對於Python 2.6,您可以將{k: v for k,v in iterator}替換為:

dict((k,v) for k,v in iterator)

您可以在這個問題中閱讀更多有關此的內容

編碼愉快!

這是適用於python2.7.x和python 3.x的一些解決方案:

data = [
    {'fips': '01001', 'state': 'AL', 'name': 'Autauga County'},
    {'fips': '20005', 'state': 'KS', 'name': 'Atchison County'},
    {'fips': '47145', 'state': 'TN', 'name': 'Roane County'},
    {'fips': 'xxx', 'state': 'yyy'}
]

output = {item['name']: 'United States' for item in data if 'name' in item}
print(output)

循環/發電機版本為:

location_list = [{'fips': '01001', 'state': 'AL', 'name': 'Autauga County'},
        {'fips': '20005', 'state': 'KS', 'name': 'Atchison County'},
        {'fips': '47145', 'state': 'TN', 'name': 'Roane County'}]
location_dict = {location['name']:'United States' for location in location_list}

輸出:

{'Autauga County': 'United States', 'Roane County': 'United States',
 'Atchison County': 'United States'}

如果您在Stackoverflow上搜索字典推導,則使用{ }生成器表達式的解決方案開始出現: Python字典推導

那應該幫你

states_dict = [{'fips': '01001', 'state': 'AL', 'name': 'Autauga County'}, {'fips': '20005', 'state': 'KS', 'name': 'Atchison County'}, {'fips': '47145', 'state': 'TN', 'name': 'Roane County'}]

{states_dict[i]['name']:'United States' for i, elem in enumerate(states_dict)}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM