我想从下面的列表中创建一个字典
[{'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 循环来做到这一点,但我想学习如何使用字典理解来做到这一点。
请您参考如下方法:
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
编码愉快!
