将dict的列表转换成dict的典雅的方式 [英] Elegant way to transform a list of dict into a dict of dicts

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

问题描述

我有一个这样的字典列表:

I have a list of dictionaries like in this example:

listofdict = [{'name': 'Foo', 'two': 'Baz', 'one': 'Bar'}, {'name': 'FooFoo', 'two': 'BazBaz', 'one': 'BarBar'}]

我知道每个字典(以及其他键)中都存在名称,它是唯一的,不会出现在列表中的任何其他字典。

I know that 'name' exists in each dictionary (as well as the other keys) and that it is unique and does not occur in any of the other dictionaries in the list.

我想用一个很好的方式通过使用键'name'来访问'two'和'one'的值。我猜字典字典会最方便吗?喜欢:

I would like a nice way to access the values of 'two' and 'one' by using the key 'name'. I guess a dictionary of dictionaries would be most convenient? Like:

{'Foo': {'two': 'Baz', 'one': 'Bar'}, 'FooFoo': {'two': 'BazBaz', 'one': 'BarBar'}}

有了这个结构,我可以轻松地遍历名称,并通过使用名称作为关键字获取其他数据。你有什么其他的数据结构建议吗?

Having this structure I can easily iterate over the names as well as get the other data by using the name as a key. Do you have any other suggestions for a data structure?

我的主要问题是:什么是最好和最Pythonic的方式进行这种转换?

My main question is: What is the nicest and most Pythonic way to make this transformation?

推荐答案

d = {}
for i in listofdict:
   d[i.pop('name')] = i

如果你有Python2.7 +:

if you have Python2.7+:

{i.pop('name'): i for i in listofdict}

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

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