0

If I got this line of code:

my_list = [3,4,7,2,1,6,8,2,1,4]

I can sort this list with:

my_list.sort()

But if I want to create a product list, For example: 2 milks, 3 cookies and so on, if I will sort this list [3,2] I will not be able to know how many milk should I buy or cookies. My question is how can I use dictionary or list so I would be able to sort the list/dictionary and also know the product name after the sort.

Saga
  • 67
  • 1
  • 8

2 Answers2

3

Put the values in tuples and they will stay together.

>>> L = [(3, 'cookies'), (2, 'milk')]
>>> L
[(3, 'cookies'), (2, 'milk')]
>>> L.sort()
>>> L
[(2, 'milk'), (3, 'cookies')]

The number must come first as when tuples are compared, first the first element is compared, then the second, etc. This is called lexicographical order.

Alex Hall
  • 34,833
  • 5
  • 57
  • 89
3

Well it depends on how you represent your product list. Say however we represent it as a list of tupes:

product_list = [(2,'milk'),(3,'cookie')]

Now you can sort with a key and set reverse on True to sort in descending order:

product_list.sort(reverse=True, key=lambda x: x[0])

So now we sort on the first item of each tuple and we do it in descending order. This will result in:

>>> product_list
[(3, 'cookie'), (2, 'milk')]
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555