Aman Mathur Aman Mathur - 9 months ago 25
Python Question

Printing and formatting a tuple in python

I have this:

record = (u'U9', [(u'U2', 1.0), (u'U10', 0.6666666666666666), (u'U2', 1.0)])


I want this as an printed output to a file:

U9:U2,U10


Note: Only unique values are needed in the output ( U2 is printed only once despite appearing twice)

I have tried using:

for i in record[1]:
print record[1], ":", record[i[0]]


But this gives me:

U9:U2
U9:U10
U9:U2

Answer Source

Extract the unique values into a set, then join those into a single string:

unique = {t[0] for t in record[1]}
print '{}:{}'.format(record[0], ','.join(unique))

Demo:

>>> record = (u'U9', [(u'U2', 1.0), (u'U10', 0.6666666666666666), (u'U2', 1.0)])
>>> unique = {t[0] for t in record[1]}
>>> print '{}:{}'.format(record[0], ','.join(unique))
U9:U10,U2

Note that sets are unordered, which is why you get U10,U2 for this input, and not U2,U10. See Why is the order in dictionaries and sets arbitrary?

If order matters, convert your list of key-value pairs to an collections.OrderedDict() object, and get the keys from the result:

>>> from collections import OrderedDict
>>> unique = OrderedDict(record[1])
>>> print '{}:{}'.format(record[0], ','.join(unique))
U9:U2,U10