0

mylist = [('Action',1) , ('Horror',2) , ('Adventure',0) , ('History',2) , ('Romance',1) ,('Comedy',1)]

i have a list of tuples like that:

Action: 1
Horror: 2
Adventure: 0
History: 2
Romance: 1
Comedy: 1

i want to sort this by two elements (name(Alphabetically) & value)

my result should be :

History: 2
Horror: 2
Action: 1
Comedy: 1
Romance: 1
Adventure: 0
Mikev
  • 2,012
  • 1
  • 15
  • 27
Nima
  • 45
  • 8

2 Answers2

0

The following should work:

from operator import itemgetter

sorted_list = sorted(mylist, key=itemgetter(0,1), reverse=True)

You can read more about this approach in the "Operator Module Functions" section of this doc: https://wiki.python.org/moin/HowTo/Sorting/

David Breen
  • 247
  • 1
  • 8
0
from collections import defaultdict

mylist = [('Action',1) , ('Horror',2) , ('Adventure',0) , ('History',2) , ('Romance',1) ,('Comedy',1)]

category = defaultdict(list)

for item in mylist:
    category[item[1]].append(item[0])

sorted(category.items())
keylist = category.keys()
for key in sorted(keylist, reverse = True):
    valuelist = category[key]
    valuelist.sort()
    category[key] = valuelist
    for v in valuelist:
        print(str(v),str(key))

Output is below:

History 2
Horror 2
Action 1
Comedy 1
Romance 1
Adventure 0
forever_software
  • 145
  • 1
  • 15