[英]Convert a list of dictionaries to a dictionary
I have a list of dictionaries in Python 我有一个Python字典列表
[
{'id':'1', 'name': 'a', 'year': '1990'},
{'id':'2', 'name': 'b', 'year': '1991'},
{'id':'3', 'name': 'c', 'year': '1992'},
{'id':'4', 'name': 'd', 'year': '1993'},
]
I want to turn this list into a dictionary of dictionaries with the key being the value of name
. 我想将此列表转换成词典的字典,键是
name
的值。 Note here different items in the list have different values of name
. 请注意,列表中的不同项目具有不同的
name
值。
{
'a': {'id':'1', 'year': '1990'},
'b': {'id':'2', 'year': '1990'},
'c': {'id':'3', 'year': '1990'},
'd': {'id':'4', 'year': '1990'}
}
What is the best way to achieve this? 实现此目标的最佳方法是什么? Thanks.
谢谢。
This is similar to Python - create dictionary from list of dictionaries , but different. 这类似于Python-从字典列表创建字典 ,但有所不同。
You can also achieve this using Dictionary Comprehension . 您也可以使用Dictionary Comprehension实现此目的。
data = [
{'id':'1', 'name': 'a', 'year': '1990'},
{'id':'2', 'name': 'b', 'year': '1991'},
{'id':'3', 'name': 'c', 'year': '1992'},
{'id':'4', 'name': 'd', 'year': '1993'},
]
print {each.pop('name'): each for each in data}
Results :- 结果:-
{'a': {'year': '1990', 'id': '1'},
'c': {'year': '1992', 'id': '3'},
'b': {'year': '1991', 'id': '2'},
'd': {'year': '1993', 'id': '4'}}
def to_dict(dicts):
if not dicts:
return {}
out_dict = {}
for d in dicts:
out_dict[d.pop('name')] = d
return out_dict
z = [
{'id':'1', 'name': 'a', 'year': '1990'},
{'id':'2', 'name': 'b', 'year': '1991'},
{'id':'3', 'name': 'c', 'year': '1992'},
{'id':'4', 'name': 'd', 'year': '1993'},
]
dict_ = {indic['name']:{
k:indic[k] for k in indic if k != 'name'} for indic in z}
try like this: 尝试这样:
>>> my_list = [
{'id':'1', 'name': 'a', 'year': '1990'},
{'id':'2', 'name': 'b', 'year': '1991'},
{'id':'3', 'name': 'c', 'year': '1992'},
{'id':'4', 'name': 'd', 'year': '1993'},
]
>>> my_dict = {}
>>> for x in my_list:
... my_dict[x['name']] = dict((key, value) for key,value in x.items() if key!='name')
...
>>> my_dict
{'a': {'id': '1', 'year': '1990'}, 'c': {'id': '3', 'year': '1992'}, 'b': {'id': '2', 'year': '1991'}, 'd': {'id': '4', 'year': '1993'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.