Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem combining two tuples into dictionary

I have a list of sorted integer IDs like

[1, 2, 10, 15, 16, 17, 20, 34, ...]

I have a tuple (tuple1) of tuples of codes next to an ID sorted by ID like

((1, "A"), (2, "A"), (15, "B"), (16, "A"), (17, "B"), (34, "B"), ...)

I have another tuple (tuple2) of tuples in the same format like

((1, "B"), (2, "B"), (10, "B"), (16, "A"), (17, "B"), (34, "B"), ...)

I want to combine the tuples into a dictionary whereby the key is the ID and the value is a list containing their code from tuple1 and their code from tuple2 in that order. If the ID exists in the ID list but not in the tuple then the value should be "N/A".

Therefore, using the above data the following should be produced:

{1: ["A", "B"], 2: ["A", "B"], 10: ["N/A", "B"], 15: ["B", "N/A"],
 16: ["A", "A"], 17: ["B", "B"], 20: ["N/A", "N/A"], 34: ["B", "B"]}

I have spent quite a while thinking about this problem but I cannot come up with a solution. If someone could help me figure out how to get it working in Python then that would be extremely helpful.

Thanks.

EDIT: It is not a duplicate, this problem is considerably more complex.

like image 647
Jack P Avatar asked Dec 10 '22 03:12

Jack P


1 Answers

If you make your tuple of tuples into a dictionary, it will be a lot easier. Use get to set a default value for your dictionary if the key is absent:

ids = [1, 2, 10, 15, 16, 17, 20, 34]
tup1 = ((1, "A"), (2, "A"), (15, "B"), (16, "A"), (17, "B"), (34, "B"))
tup2 = ((1, "B"), (2, "B"), (10, "B"), (16, "A"), (17, "B"), (34, "B"))

tup1 = dict(tup1)
tup2 = dict(tup2)    
{k: [tup1.get(k, 'N/A'), tup2.get(k, 'N/A')] for k in ids}
like image 181
busybear Avatar answered Dec 21 '22 17:12

busybear