Python字典理解列表的字典

时间:2017-01-25 11:13:56

标签: python dictionary

我想从以下列表中创建一个字典

[{'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来完成它。

4 个答案:

答案 0 :(得分:6)

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)

您可以阅读有关此in this question

的更多信息

快乐的编码!

答案 1 :(得分:2)

这是一个适用于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)

答案 2 :(得分:-1)

循环/生成器版本是:

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 Dictionary Comprehension

答案 3 :(得分:-2)

那应该为你做的伎俩

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)}
相关问题