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.
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}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With