Deleted
Deleted

Reputation: 4217

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?

Upvotes: 7

Views: 250

Answers (2)

JBernardo
JBernardo

Reputation: 33397

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

if you have Python2.7+:

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

Upvotes: 14

agf
agf

Reputation: 176780

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 names, you can still easily do it in one line:

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

Upvotes: 5

Related Questions