我想从以下列表中创建一个字典
[{'fips': '01001', 'state': 'AL', 'name': 'Autauga County'}, {'fips': '20005', 'state': 'KS', 'name': 'Atchison County'}, {'fips': '47145', 'state': 'TN', 'name': 'Roane County'}]
Run Code Online (Sandbox Code Playgroud)
结果应该是名称作为键,"美国"作为值.
例如:
{'Autauga County': 'United States', 'Atchison County' : 'United States', 'Roane County' : 'United States'}
Run Code Online (Sandbox Code Playgroud)
我可以通过几个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}
Run Code Online (Sandbox Code Playgroud)
一些学习笔记:
{}(和键)[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'
Run Code Online (Sandbox Code Playgroud)
正如评论中所提到的,对于Python 2.6,您可以替换为{k: v for k,v in iterator}:
dict((k,v) for k,v in iterator)
Run Code Online (Sandbox Code Playgroud)
您可以在此问题中阅读更多相关信息
快乐的编码!
| 归档时间: |
|
| 查看次数: |
1517 次 |
| 最近记录: |