views:

86

answers:

3

Hello! You have list of objects each of them have id property. Here's my way to covert 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.

+6  A: 

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)
JAB
+5  A: 
dict([(x.id, x) for x in list])
tlayton
works in Python 2.x
tlayton
you don't need list comprehension there
SilentGhost
Indeed. As stated in my answer, a generator expression is better.
JAB
A: 
dict(map(lambda x: [x.id, x], list))
sepp2k
He wants id, not length.
JAB
@JAB: Oops, dunno how I came up with length.
sepp2k