Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

reverse sorting gone wrong in python

I am trying to create a script, that will get a tuple, sort it by value AND by name- for example if I have:

((‘apple’, 5), (‘tv’, 500), (‘bee’, 1000), (‘cat’, 500))

I want it to return:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[‘bee’, ‘cat’, ‘tv’, ‘apple’]

so that the item with the biggest number will be first, but if two items have the same value the one that is lexicographically smaller will appear first.
this is my code:

def find_k_most_expensive_products(data, k):
    executed_file = executeMtmikya(data)
    sorted_prices_tup = sorted(executed_file[2], reverse=True, key=lambda element: 
                              (executed_file[2][1], executed_file[2][0]))
    best_sellers = []

    print("------------")
    print("this is the sorted prices_tup: ")
    print(sorted_prices_tup)
    print("------------")
    for i in sorted_prices_tup:
        while k > 0:
            best_sellers.append(i[1])
            print("k is- ")
            print(k)
            break
        k -= 1
    return best_sellers

But this is what I get instead, given:

{‘apple’: ‘5’, ‘tv’: ‘500’, ‘bee’: ‘1000’}

------------
this is the sorted prices_tup: 
[('5', 'apple'), ('500', 'tv'), ('1000', 'bee')]
------------
k is- 
3
k is- 
2
k is- 
1
['apple', 'tv', 'bee']

Why isn’t it working as expected?

>Solution :

As you got a hint, you need to use the key parameter ofsorted. You however did not do it correctly as your lambda does not use the object that is passed as parameter.

One option is to take the opposite of the number as first key for reverse sorting, and the word as second key for lexicographic sorting:

t = (('apple', 5), ('tv', 500), ('bee', 1000), ('cat', 500))

[x for x,_ in sorted(t, key=lambda x: (-x[1], x[0]))]

Output: ['bee', 'cat', 'tv', 'apple']

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading