简体   繁体   English

将dict列表转换为dicts字典的优雅方式

[英]Elegant way to transform a list of dict into a dict of dicts

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',并且它是唯一的,并且不会出现在列表中的任何其他字典中。

I would like a nice way to access the values of 'two' and 'one' by using the key 'name'. 我想通过使用键'name'来访问'two'和'one'的值。 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? 您对数据结构有任何其他建议吗?

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

if you have Python2.7+: 如果你有Python2.7 +:

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

is the easiest if you don't mind the name key remaining in the dict . 如果你不介意dict剩下的name键,这是最简单的。

If you want to remove the name s, you can still easily do it in one line: 如果要删除name s,您仍然可以在一行中轻松完成:

dict(zip([d.pop('name') for d in listofdict], listofdict))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM