-1

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Aman Mathur
  • 709
  • 2
  • 15
  • 27
  • By what rules are the values extracted from the list? Unique values only? In what order? I'm presuming that you only want to print `U2` once even though it appears twice. Please be *explicit* about what the rules are. – Martijn Pieters Mar 12 '17 at 05:38
  • Thank you. I have edited it now. – Aman Mathur Mar 12 '17 at 05:42

1 Answers1

2

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thank you for this. Also, if I want them ordered (U2,U10) what can I add to the above? – Aman Mathur Mar 12 '17 at 05:49
  • @AmanMathur: you could use an `OrderedDict`; added that as an alternative. – Martijn Pieters Mar 12 '17 at 05:51
  • Thanks you again. But strangely it does not order if the record = (u'U9', [(u'U10', 0.6666666666666666), (u'U2', 1.0)]) I am still getting U9:U10,U2 – Aman Mathur Mar 12 '17 at 06:02
  • 1
    @AmanMathur: That's a *different order* from the input. Please be *explicit* about what order you want. You appear to want to *sort* the key, using a *natural order* (so only using the numbers). Use the set version, then sort that first using the answers from [Does Python have a built in function for string natural sort?](//stackoverflow.com/q/4836710) – Martijn Pieters Mar 12 '17 at 06:05
  • Thank you. I however cannot use third party libraries for sorting. – Aman Mathur Mar 12 '17 at 06:12
  • @AmanMathur: please check **all** answers on that question. Only the accepted answer requires an external library. – Martijn Pieters Mar 12 '17 at 06:16
  • data.sort(key=lambda x: '{0:0>8}'.format(x).lower()) this one worked for me. Instead of tuple I had to use a list. Thank you. :) – Aman Mathur Mar 12 '17 at 06:21