tags:

views:

38

answers:

3

Every example of list or set usage in Python seems to include trivial cases of integers but I have two lists of objects where the name attribute defines whether two objects instances are "the same" or not (other attributes might have different values).

I can create a list that contains all items from both lists, sorted, with

tmpList = sorted(list1 + list2, key=attrgetter('name'))

but how do I do the same so that list items that have the same value in the name attribute are selected from the second list?

E.g combining these two lists

list1 = [obj('Harry',18), obj('Mary',27), obj('Tim', 7)]
list2 = [obj('Harry', 22), obj('Mary', 27), obj('Frank', 40)]

would result in

list = [obj('Harry',22), obj('Mary', 27), obj('Tim', 7), obj('Frank', 40)]

(I used obj() as a short-hand notation for an object that has two attributes.)

It seems like I can't use the attrgetter() function in most set and list functions like I can with the sorted() function so I can't figure out how I'm supposed to do this. I suspect I could use a lambda function, but I'm not too familiar with functional programming so I don't seem to manage to figure it out.

The naive solution (first pick all items that are unique in both lists and then combine that list with what is left of the second list) seems quite long-winded so there must be a simpler way in Python.

+2  A: 

Sounds to me like you might be better off with a dict instead of a list, using the name as the key, and the rest of the object as value. Then you can simply dict1.update(dict2).

>>> dict1 = {"Harry": 18, "Mary": 27, "Tim": 7}
>>> dict2 = {"Harry": 22, "Mary": 27, "Frank": 40}
>>> dict1.update(dict2)
>>> dict1
{'Tim': 7, 'Harry': 22, 'Frank': 40, 'Mary': 27}
Tim Pietzcker
OK, thanks, now it works! I've been trying to get this to work all morning, so this was great help!
Makis
+1  A: 

Yes. The easy way is a dictionary.

list1 = {"Harry": 18, "Mary": 27, "Tim": 7}
list2 = {"Harry": 22, "Mary": 27, "Frank": 40}

list1.update(list2)

list is now {'Harry':22, 'Mary': 27, 'Tim': 7, 'Frank': 40}

If your data is more than just a number, that's OK. You can put any kind of object as the value for a dictionary.

list1['Harry'] = (1,"weee",54.55)
JoshD
I accepted Tim's answer because it was very slightly more comprehensible thanks to the first paragraph, but thank's for your answer as well.
Makis
A: 

You can implement de __eq__ attribute in your object. Based on that you can compare your objects with the == operator.

ssoler