Gabriel Gonzalez
Gabriel Gonzalez

Reputation: 11

overload sorting in python

I have a dictionary with two fields: a string field and a numeric field.

First the ordering must be by value.

In case of being tied with another, another order must be made by key.

I think it is an overload of the ordering.

present = {
    '35':10,
    '20':10,
    '10':50
}
sortedPresent = sorted(present.items(), key=lambda kv: kv[1], reverse=True)

The output is:

[('10', 50), ('35', 10), ('20', 10)]

Expected output:

[('10', 50), ('20', 10), ('35', 10)]

Upvotes: 1

Views: 115

Answers (1)

DarrylG
DarrylG

Reputation: 17166

sortedPresent = sorted(present.items(), key=lambda kv: (-kv[1], kv[0]))
# We sort by tuples as described
#      https://www.peterbe.com/plog/in-python-you-sort-with-a-tuple
# Note for tuple as key:
#   -k[1] is descending order by number
#   k[0] is ascending order by string
print(sortedPresent)

Output

[('10', 50), ('20', 10), ('35', 10)]

Upvotes: 3

Related Questions