将字典列表转换为字典 [英] Convert a list of dictionaries to a dictionary

查看:249
本文介绍了将字典列表转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python中的字典列表

I have a list of dictionaries in 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'},
]

我想把这个列表变成一个字典键值为名称的字典。请注意,列表中的不同项目具有不同的值 name

I want to turn this list into a dictionary of dictionaries with the key being the value of name. Note here different items in the list have different values of 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.

这与 Python - 从词典列表中创建词典,但不同。

推荐答案

您也可以使用词典解读

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}  

结果: -

{'a': {'year': '1990', 'id': '1'}, 
 'c': {'year': '1992', 'id': '3'}, 
 'b': {'year': '1991', 'id': '2'}, 
 'd': {'year': '1993', 'id': '4'}}

这篇关于将字典列表转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆