-2

I have data that has been arranged in the following format

products{} = {'001':['001','Espreso',2.50], 
              '002':['002', 'Latte',1.50], 
              '003':['003', 'Orange Juice',1.00],
              '004':['003', 'Apple Juice',1.00], 
              }

I would like to sort the dictionary based on price so that I can get the following output.

products{} = {'003':['003', 'Orange Juice',1.00],
              '004':['003', 'Apple Juice',1.00],
              '002':['002', 'Latte',1.50],
              '001':['001','Espreso',2.50], 
              }

Being a newbie to python, I cant seem to find a proper guidance to sort this. I have an array as value.

Please guide how to achiece this? Is this even a correct way of assigning array as value to a key.? Is this known as ordered dictionary?

rasul1719435
  • 115
  • 4
  • 10

1 Answers1

0

To sort dictionary you can pass it's items into a sorted() and initialize new dictionary from sorted key-value pairs.

To sort items of your dictionary by last element of value, we should pass to key argument of sorted() a lambda which will return receive key-value pair and return last element (-1 index) of value (1 index).

Code:

products = {
    '001':['001','Espreso',2.50], 
    '002':['002', 'Latte',1.50], 
    '003':['003', 'Orange Juice',1.00],
    '004':['003', 'Apple Juice',1.00]
}
sorted_products = dict(sorted(products.items(), key=lambda x: x[1][-1]))
Olvin Roght
  • 7,677
  • 2
  • 16
  • 35
  • ````sorted_products = dict(sorted(products.items(), key=lambda x: x[1][1]))``` So If I want to sort via the name, I need to replace -1 to 1 – rasul1719435 Jul 30 '21 at 10:06
  • Please note that this only works with python 3.7 or higher, as explained in the answer to this question: https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value – Stef Jul 30 '21 at 10:17
  • @rasul1719435, yes, you're right, name is the second element with index `1`. – Olvin Roght Jul 30 '21 at 10:47
  • @Stef, this is the last year when python 3.6 is supported, so I think it's not necessary to mention that anymore. – Olvin Roght Jul 30 '21 at 10:50
  • @rasul1719435, if my answer helped you consider [to accept](https://stackoverflow.com/help/someone-answers) it. – Olvin Roght Jul 30 '21 at 12:09