简体   繁体   中英

Find common values from 2 list of tuples and add the values from one tuple to another

I have 2 lists with tuples as their elements. One element of tuple is to be matched to the tuple from other list and corresponfing values are to be added from one tuple to another.

My 2 lists are:

l1 = [('Receipt total', 10),('Total Amount (AED)', 10),('Grand total', 10),('Net Amount', 9),
 ('Total Amount', 9),('Total (words are in between)', 6)]

l2 = [('Total Amount', ['593.52']), ('Total (words are in between)', ['593.52'])]

The keys Total Amount and Total (words are in between) in l2 are to be matched from l1 and the value corresponding to keys present in l1 9 and 6 respectively in this case are to be added to either l2 or a new list.

Expected output:

l2 = [('Total Amount', ['593.52'],[9]), ('Total (words are in between)', ['593.52'],[6])]

I'll be happy to provide further clarification and I am unable to think about this would happen and I am sorry if this seems too messy and I looked for similar questions but nothing seemed apt Thank you!

For readability I would create a temporarily dictionary of the l1 to easier do the look-up on the keys.

Unpack the tuples in l2 and compare the keys with those in the l1 -dictionary. Create a new tuple if match and wrap everything in a list

l1_map = {k: v for k, v in l1}
l2_updated = [(key, num, [l1_map[key]]) for key, num in l2 if key in l1_map]

Result:

[('Total Amount', ['593.52'], [9]),
 ('Total (words are in between)', ['593.52'], [6])]

First create a dict from l1 and then alter l2:

D1=dict(l1)
l2=[t + ([D1[t[0]]],) for t in l2]

output:

[('Total Amount', ['593.52'], [9]), ('Total (words are in between)', ['593.52'], [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