Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce list of Python objects to dict of object.id -> object

You have list of objects and each of them has an id property.

Here's my way to convert it to dict where keys are ids and values are objects:

reduce(   lambda x,y: dict(x.items() + { y.id : y}.items()),   list,   {} ) 

Suggest better way to do it.

like image 555
Dmitry Teslenko Avatar asked Jun 18 '10 14:06

Dmitry Teslenko


People also ask

What does -> dict mean in Python?

Definition and Usage The dict() function creates a dictionary. A dictionary is a collection which is unordered, changeable and indexed.

How do I convert a list to a dictionary in Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

How do I convert a nested list to a dictionary?

We can convert a nested list to a dictionary by using dictionary comprehension. It will iterate through the list. It will take the item at index 0 as key and index 1 as value.

How do you convert a list to a key value pair in Python?

For odd items we do the same but starting at index 1 . If we zip those two lists together we obtain a list of (key, value) that we can pass the return value to the dict constructor. Might add a map(str, ....) to the second part to exactly match the desired result.


2 Answers

In Python 3.x:

object_dict = {x.id: x for x in object_list} 

In both Python 3.x and Python 2.4+:

object_dict = dict((x.id, x) for x in object_list) 

(x.id, x) for x in object_list is a generator comprehension (and, nicely, does not need to be wrapped in parentheses like a list comprehension needs to be wrapped in brackets if it's being used as a single argument for a call; of course, this means that in other circumstances the expression I used would have to be ((x.id, x) for x in object_list)). Unlike a list comprehension, it will not generate an actual list of all the items, and is thus more efficient in situations such as this.

As a side note, Python has a built-in method id():

Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. (Implementation note: this is the address of the object.)

So if you wanted to let Python handle the ids on its own, you could do it as:

object_dict = {id(x): x for x in object_list} 

or

object_dict = dict((id(x), x) for x in object_list) 
like image 66
JAB Avatar answered Sep 19 '22 21:09

JAB


dict([(x.id, x) for x in list]) 
like image 34
tlayton Avatar answered Sep 20 '22 21:09

tlayton