Elegant way to convert dict list to dict dicts

I have a list of dictionaries, as in this example:

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

I know that a "name" exists in every dictionary (as well as in other keys) and that it is unique and does not appear in any of the other dictionaries in the list.

I need a good way to access the values ​​"two" and "one" using the key "name". I think the dictionary of dictionaries would be the most convenient? How:

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

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

My main question is: what is the best and most pythonic way to do this conversion?

+7
source share
2 answers
 d = {} for i in listofdict: d[i.pop('name')] = i 

if you have Python2.7 +:

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

is the easiest if you don't mind the name key left in the dict .

If you want to remove name s, you can still do this on one line:

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

All Articles