Aman Mathur Aman Mathur - 1 year ago 59
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:


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:


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))


>>> 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))

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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download