简体   繁体   中英

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.

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?

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+:

{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 .

If you want to remove the name s, you can still easily do it in one line:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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