简体   繁体   中英

Combine two lists of tuples by key

I have two lists of two elements tuples. First element of tuple is ID and second is some kind of value. Type of value depends on list.

lst1 = [ ('a', 1), ('b', 2), ('c', 3) ]
lst2 = [ ('b', 5), ('a', 4), ('c', 6) ] 

What is the easiest way to combine them into:

lst3 = [ ('a', 1, 4), ('b', 2, 5), ('c', 3, 6)]

I suggest you turn those lists of tuples into dictionaries first. Then, assuming that both lists contain the same "keys", you can use a simple list comprehension to get the respective values from the two dictionaries.

lst1 = [ ('a', 1), ('b', 2), ('c', 3) ]
lst2 = [ ('b', 5), ('a', 4), ('c', 6) ] 
dict1 = dict(lst1)
dict2 = dict(lst2)
lst3 = [(k, dict1[k], dict2[k]) for k in sorted(dict1)]

Note that dictionaries have no fixed order. If you want to preserve the order the keys had in lst1 , you might also use this, as suggested in comments:

lst3 = [(k, v, dict2[k]) for k, v in lst1]
lst1 = [ ('a', 1), ('b', 2), ('c', 3) ]
lst2 = [ ('b', 5), ('a', 4), ('c', 6) ] 

dst1 = dict(lst1)
dst2 = dict(lst2)

for i in dst1:
    if i in dst2:
        dst1[i] = (dst1[i],dst2[i])

print dst1
{'a': (1, 4), 'c': (3, 6), 'b': (2, 5)}

Then you can this format dst1 to whatever format you want the result in.

You just need to create one dict using the first element from each tuple from lst1 as the key and storing the tuple as the value, then iterate over the second list and add the last element to the corresponding tuple in the dict.

lst1 = [('a', 1), ('b', 2), ('c', 3)]
lst2 = [('b', 5), ('a', 4), ('c', 6)]
from collections import OrderedDict
d = OrderedDict(zip((tup[0] for tup in lst1), lst1))

for k,v  in lst2:
    d[k] = d[k] + (v,)
print(d.values())
[('a', 1, 4), ('b', 2, 5), ('c', 3, 6)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM