Python Sorting Tie Breaking with ascending order and descending order

Viewed 86

please help on this Sorting

 d={'d':1,'b':2,'c':3,'a':3}

what should i do to get out as ascending order by value and descending order by key.

ie

OUT=[('d', 1), ('b', 2), ('c', 3), ('a', 3)]

I know a=sorted(d.items(),key=lambda x:(x[1],-x[0])) wont work since it is alphabet and will work fine if it is a number.

1 Answers

Use ord

Ex:

d={'d':1,'b':2,'c':3,'a':3}
a=sorted(d.items(),key=lambda x:(x[1],-ord(x[0])))
print(a) 

Output:

[('d', 1), ('b', 2), ('c', 3), ('a', 3)]
Related