0

I have this array :

a = [{'id': 1, 'date: '2020-01-31'}, {'id': 2, 'date': '2020-01-25'}, {'id': 3, 'date': '2020-01-26'}]

I would like to order it by date like that :

a = [{'id': 2, 'date': '2020-01-25'}, {'id': 3, 'date': '2020-01-26'}, {'id': 3, 'date'; '2020-01-31'}]

How can I do this to sort my array like that ?

Thank you very much !

Bob
  • 103
  • 1
  • 6
  • 2
    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) – oo00oo00oo00 Nov 13 '20 at 15:54

3 Answers3

4

Simplest solution: use the built-in sorted function, and for the key default argument, use a lambda expression to extract the date of each element, as shown below:

a = [
    {'id': 1, 'date': '2020-01-31'},
    {'id': 2, 'date': '2020-01-25'},
    {'id': 3, 'date': '2020-01-26'}
]

a_sorted = sorted(a, key=lambda e: e['date'])

print(a_sorted)

Console output:

[{'id': 2, 'date': '2020-01-25'}, {'id': 3, 'date': '2020-01-26'}, {'id': 1, 'date': '2020-01-31'}]
Jake Levi
  • 1,329
  • 11
  • 16
1

If you want to sort the array on your own, you can use a sorting Algorithm, for example the bubble sort or you can check here in this link for more algorithms

0

sorted(a, key= lambda item: item['date'])

if you need descending order

sorted(a, key= lambda item: item['date'], reverse=True)

Vinay Emmaadii
  • 125
  • 1
  • 11