[英]extract data from list of dictionaries
Hi I would like to convert a list of dictionaries into a single dictionary of some of the items in the list: I have:嗨,我想将字典列表转换为列表中某些项目的单个字典:我有:
>>> print(dct_lst)
[{'id': 456, 'name': 'bar'}, {'id': 789, 'name': 'baz'}, {'id': 123, 'name': 'foo'}]
I want:我想:
dct={'bar':None
'baz':None
'foof':None}
and I've tried (among other combinations):我已经尝试过(在其他组合中):
>>> for i in dct_lst['name']:
... btns[i]=None
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
How do I get what I need?我如何得到我需要的东西?
Consider utilizing a dict comprehension :考虑使用字典理解:
>>> dct_lst = [{'id': 456, 'name': 'bar'}, {'id': 789, 'name': 'baz'}, {'id': 123, 'name': 'foo'}]
>>> dct = {d['name']: None for d in dct_lst if 'name' in d}
>>> dct
{'baz': None, 'foo': None, 'bar': None}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.