Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 785
Deleted Avatar asked Nov 28 '11 23:11

Deleted


People also ask

How do I merge a list of Dicts into a single dict?

To merge multiple dictionaries, the most Pythonic way is to use dictionary comprehension {k:v for x in l for k,v in x. items()} to first iterate over all dictionaries in the list l and then iterate over all (key, value) pairs in each dictionary.

How do you turn a list into a tuple?

Using the tuple() built-in function An iterable can be passed as an input to the tuple () function, which will convert it to a tuple object. If you want to convert a Python list to a tuple, you can use the tuple() function to pass the full list as an argument, and it will return the tuple data type as an output.


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}
like image 133
JBernardo Avatar answered Oct 03 '22 03:10

JBernardo


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))
like image 40
agf Avatar answered Oct 03 '22 03:10

agf