-1

I'll get to the point,i have this:

    ocurrencias = [('quiero', 1), ('aprender', 1), ('a', 1), ('programar', 1), ('en', 1), ('invierno', 2), ('hace', 1), ('frio', 1), ('este', 1)]

I want to sort it by the second value of the tuples and then by their string value and then print every element to get this:

    output:invierno 2
           a 1
           aprender 1
           en 1
           este 1
           frio 1
           hace 1
           programar 1
           quiero 1

Don't know if i'm making it clear enough,but i'm not really proficient at english so forgive me.

Thanks in advance

Fgbruna
  • 127
  • 7

1 Answers1

7

Use sorted with a key which makes a reversed version of each tuple, to sort the second value in descending order, you can add a - in front to negate the value:

sorted(ocurrencias, key = lambda x: (-x[1], x[0]))
# [('invierno', 2), ('a', 1), ('aprender', 1), ('en', 1), ('este', 1), ('frio', 1), ('hace', 1), ('programar', 1), ('quiero', 1)]

As commented by @Jonathon, the reason this works is due to the fact that lists and tuples comparison happens in order i.e, compare the first element; if not equal then the second element, to see more about object comparison in python.

Psidom
  • 209,562
  • 33
  • 339
  • 356
  • 1
    Simpler than my answer. Very nice. It might be worth pointing out that by default, tuples are compared first element, then second, and so on. – Jonathon Reinhart Jan 12 '17 at 01:12
  • Thanks Psidom!,i know it looks like i did close to none research but i did and none of the answers i found really clicked for me, adding it to the fact that i started learning python, as my first language, about a week ago so i'm still pretty overwhelmed by it. – Fgbruna Jan 12 '17 at 01:29
  • This answer is a convoluted way of doing this: `sorted(ocurrencias, key=lambda x: x[1], reverse=True)` – Harvey Feb 12 '17 at 03:53