-2
   products = [
        {"name": "apples", "price": "1.00", "expiration_dates": "2020-05-01"},
        {"name": "oranges", "price": "1.40", "expiration_dates": "2020-05-23"},
        {"name": "bananas", "price": "0.90", "expiration_dates": "2020-04-11"},
        {"name": "pears", "price": "1.10", "expiration_dates": "2020-06-21"},
        {"name": "peaches", "price": "0.70", "expiration_dates": "2020-04-09"},
        {"name": "apples", "price": "1.00", "expiration_dates": "2020-05-10"},
    ]

(new to python)

I would like to know how I could sort this dictionary by name(alphabetical order), price and date.

  • Does this answer your question? [How do I sort a list of dictionaries by a value of the dictionary?](https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary) – Rakesh Mar 11 '20 at 13:44
  • Use `list.sort` or `sorted` on your array. – LeoDog896 Mar 11 '20 at 13:44

1 Answers1

0

That's not a dictionary, that's a list of dictionaries. You can't sort an individual dictionary (they're inherently unordered - key-based) but you can sort the list of dictionaries that you have.

You do this with either the built-in sorted() or list.sort(), giving it a key argument that specifies the criteria you want to sort on.

For example:

print(sorted(products, key=lambda d: (d['name'], d['price'], d['expiration_dates'])))
#[{'name': 'apples', 'price': '1.00', 'expiration_dates': '2020-05-01'}, 
# {'name': 'apples', 'price': '1.00', 'expiration_dates': '2020-05-10'},
# {'name': 'bananas', 'price': '0.90', 'expiration_dates': '2020-04-11'},
# {'name': 'oranges', 'price': '1.40', 'expiration_dates': '2020-05-23'},
# {'name': 'peaches', 'price': '0.70', 'expiration_dates': '2020-04-09'},
# {'name': 'pears', 'price': '1.10', 'expiration_dates': '2020-06-21'}]

The key is a lambda function that returns the arguments of interest, for each element of the list being sorted, in order. When there's a tuple, the criteria are weighted in-order: only if name is equal does it go on to price, only if price is equal does it go on to expiration date, etc.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53