Reputation: 28088
I have this tuple of tuples;
Tup1= ( ('AAA', 2), ('BBB', 3) )
I have another tuple;
Tup2 = ('AAA', 'BBB', 'CCC', 'DDD')
I want to compare Tup1
and Tup2
. Based on the comparison, I want to create another tuple of tuples that look like this;
OutputTup = ( ('AAA', 2), ('BBB', 3), ('CCC', 0), ('DDD', 0) )
The logic is like this. Look into every element inside Tup2 and then look for matching element in Tup1. If there is matching element(example 'AAA') in Tup1, copy to OutputTup ('AAA', 2). If there is no matching element (example 'CCC'), then assign a value of 0 and append to OutputTup ('CCC', 0).
How can this be done in Python 2.7? Thanks.
Upvotes: 0
Views: 778
Reputation: 8702
for some extend .please edit my answer . i cannot figure how to check type. if some one know feel free to edit my answer
from itertools import izip,izip_longest
Tup1= ( ('AAA', 2), ('BBB', 3) )
Tup2 = ('AAA', 'BBB', 'CCC', 'DDD')
lis=[ i if type(i[0])==type(0) else i[0] for i in list(izip_longest(Tup1, Tup2 , fillvalue=0))]
#output [('AAA', 2), ('BBB', 3), (0, 'CCC'), (0, 'DDD')]
Upvotes: 2
Reputation: 363
This also works with the output you want:
tup1 = ( ('AAA', 2), ('BBB', 3) )
tup2 = ('AAA', 'BBB', 'CCC', 'DDD')
dic = dict( tup1 )
for tri in tup2:
dic[tri] = dic.get(tri,0)
print tuple(dic.items())
#(('AAA', 2), ('BBB', 3), ('CCC', 0), ('DDD', 0))
Upvotes: 3