0

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.

guagay_wk
  • 26,337
  • 54
  • 186
  • 295

2 Answers2

3

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))
yoopoo
  • 343
  • 1
  • 2
  • 10
  • It was quite brilliant to convert the tuple into a dictionary. I got stuck trying to use a while loop to do the comparison for each element in the tuple. Upvoted! – guagay_wk Jun 27 '14 at 07:42
  • this will not keep the original information if there are duplicates in the first values – omu_negru Jun 27 '14 at 07:43
  • @yoopoo: Thanks. Elegant and easy to understand. Voted as the right answer. – guagay_wk Jun 27 '14 at 07:59
2

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')]
sundar nataraj
  • 8,524
  • 2
  • 34
  • 46
  • Thanks. Although it is not the answer as the output tuple is not exactly what is wanted, I learnt something new about itertools. Upvoted. – guagay_wk Jun 27 '14 at 07:36
  • Use type? Not sure if this is right. http://stackoverflow.com/questions/402504/how-to-determine-the-variable-type-in-python – guagay_wk Jun 27 '14 at 07:51
  • nataraj Сундар : thank you for the answer. Your answer is also correct but I am sorry I can only vote for only 1 right answer. I chose the other answer because it does not need to import from another module. It is also easier for me to understand. – guagay_wk Jun 27 '14 at 07:59