comparing two lists
Erik Jones
erik at myemma.com
Thu Aug 23 13:44:21 EDT 2007
On Aug 23, 2007, at 11:27 AM, Ladislav Andel wrote:
> Hi,
> what would be the most efficient way to do following?
>
> I have a list of dictionaries taken from DB e.g.
> dblist = [{'id:1, 'host':'google.com','ip_address':'1.2.3.4'},
> {'id:3, 'host':'yahoo.com','ip_address':'5.6.7.8'},
> {'id:9, 'host':'msn.com','ip_address':'11.3.2.3'}]
>
> and list of object instances in memory(it's just for example)
> which are looping within itself and testing particular hosts
>
> memlist = [<instance 1>,<instance 2>]
> memlist[0].id is 1 and memlist[0].host is google.com etc.
> memlist[1].id is 9 and memlist[1].host is msn.com etc.
>
> Now I want to add a new instance to memlist since id=3(in dblist)
> is not
> in memlist.
> How would you iterate through it and insert a new instance?
>
> The result should be:
> memlist = [<instance 1>,<instance 2>, <instance 3>]
> memlist[0].id is 1 and memlist[0].host is google.com etc.
> memlist[1].id is 3 and memlist[1].host is yahoo.com etc.
> memlist[2].id is 9 and memlist[2].host is msn.com etc.
Well, if you add a constructor for object instances that can take
those dictionaries you could do something like:
for row in dblist.iteritems():
obj = Obj(row) # where Obj is your classname
if obj is not in memlist:
memlist.append(obj)
>
> Furthermore, I can have the opposite situation.
> This time I need to remove from memlist a host which is not in dblist.
> How would you do this?
Similarly, if you add an toHash() method to you object class you
could do something like (using the reverse iteration solution
mentioned in another reply):
for i in range(len(memlist) -1, -1, -1):
if memlist[[i].toHash() not in dblist:
del memlist[i]
Erik Jones
Software Developer | Emma®
erik at myemma.com
800.595.4401 or 615.292.5888
615.292.0777 (fax)
Emma helps organizations everywhere communicate & market in style.
Visit us online at http://www.myemma.com
More information about the Python-list
mailing list