[Python] Get top three items with unique value from dictionary

Discussão em 'Python' iniciado por Stack, Setembro 13, 2021.

  1. Stack

    Stack Membro Participativo

    I have the following dictionary

    dict1 = {'apple':50,'banana':20,'orange':50,'peach':20,
    'mango':10}


    I know how to get the top three items using the following:

    def test(x):
    return x[1]

    sorted(dict1.items(), key=test, reverse=True)[:3]


    and I got

    [('apple', 50), ('orange', 50), ('banana', 20)]


    But notice that apple and orange are of the same value which is 50.

    How do I modify the code to get output like this?

    [('apple', 50), ('banana', 20), ('mango', 10)]


    or

    [('orange', 50), ('peach', 20), ('mango', 10)]


    So only one of the two fruits with the same value would be listed at random.

    I am not sure where to implement random.choice to get one of the two fruits of the same value at random.

    Continue reading...

Compartilhe esta Página