[英]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}
一些学习注意事项:
{}
(和键)除外 [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.