Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving from list of objects by id

In the following code I create a list of three objects and use the variable a,b,c to store the first, second and then the third object by their id's but when I try to store the third object in variable c, it stores a list of the second and third object.

class Obj1():
    id='obj1'

class Obj2():
    id='obj2'

class Obj3():
    id='obj3'

list1=[Obj1(),Obj2(),Obj3()]

a=list1[id=="obj1"]
print a

b=list1[id!='obj1']
print b

c=list1[id!='obj1'and id!='obj2':]
print c

When I run this code I get :

<__main__.Obj1 instance at 0x02AD5DA0>
<__main__.Obj2 instance at 0x02AD9030>
[<__main__.Obj2 instance at 0x02AD9030>, <__main__.Obj3 instance at 0x02AD90A8>]

why does variable c contain two objects?

like image 291
Rmor91 Avatar asked Oct 21 '25 03:10

Rmor91


2 Answers

Using a dictionary is probably the best idea in this case, as mentioned by Medhat. However, you can do things in a similar way to what you attempted using list comprehensions:

a = [e for e in list1 if e.id == "obj1"]
print a

b = [e for e in list1 if e.id != "obj1"]
print b

c = [e for e in list1 if e.id != "obj1" and e.id != "obj2"]
# Or:
# [e for e in list1 if e.id not in ("obj1", "obj2")]
print c
like image 178
JKillian Avatar answered Oct 22 '25 23:10

JKillian


You should use a dictionary instead:

obj1 = Obj1()
obj2 = Obj2()
obj3 = Obj3()
list1 = {obj1.id: obj1, obj2.id: obj2, obj3.id: obj3}

Then access your objects like this:

a = list1[obj1.id]
b = list1[obj2.id]
c = list1[obj3.id]
like image 45
Medhat Gayed Avatar answered Oct 23 '25 00:10

Medhat Gayed