lambda - reduce python list of objects to dict object.id -> object -


You have a list of objects, each of them has ID assets here. This is my way to keep this keyboard secret. Where the keys are id and values ​​are objects:

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

Recommend a better way to do this.

In Python 3.x:

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

Both Python 3.x and Python 2.4+:

  object_dict = dict (x.id, x) ) Object_list in x)  

(x .id, x) object_list is a generator to understand for x (and, well, let's wrapped in brackets Is not required as if the list needs to be wrapped in the brackets if it is being used as a single logic call, Hir, it means that the use of which I expression in other circumstances, therefore, it should be (x.id, x) x in object_list) ). Contrary to the understanding of a list, it will not generate the actual list of all the objects, and thus more efficient in the circumstances.

In the form of a side note, Python has an underlying method Id () :

Return the "identity" of an object. It is an integer that guarantees to be unique and stable for this object in its lifetime. Two objects with non-overlapping births can have the same ID () value. (Implementation note: This is the address of the object.)

So if you want to handle Python on your own ID, you can do this:

 X  

or

  object_dict = dict ((id (x)) in  object_dict = {object (id): x} , X) for the object_list in the list)     

Comments