Search code examples
pythonsortingdictionarylambdadictionary-comprehension

Sorting the dictionary by values


sort_orders = sorted(orders.items(), key=lambda x: x[1], reverse=True)

Can someone explain how key=lambda x: x[1] works to sort the dictionary by values?


Solution

  • dict.items() returns itemview object. It is something like:

    dict_items([('key_1', 'val_1'), ('key_2', 'val_2'), ('key_3', 'val_3')])
    

    so if you pass this object to sorted and put in the key argument as lambda x: x[1] it will sort the itemview object basis the first index of every tuple inside the itemview. It will further set that order as descending as the reverse argument is set to True

    If I try to explain this via an example consider this:

    orders={'order_1':'Pizza','order_2':'Chicken','order_3':'Lasagne'}
    
    sort_orders = sorted(orders.items(), key=lambda x: x[1], reverse=True)
    
    print(sort_orders) #1
    
    print(orders.items()) #2
    

    The #1 Print gives you:

    [('order_1', 'Pizza'), ('order_3', 'Lasagne'), ('order_2', 'Chicken')]
    

    The #2 Print gives you:

    dict_items([('order_2', 'Chicken'), ('order_1', 'Pizza'), ('order_3', 'Lasagne')])
    

    Visit this python documentation on sorting for more information related to sorted

    Hope this helps !