-2

My data is in the form: [{'value': 2, 'year': u'2015'}, {'value': 4, 'year': u'2016'}, {'value': 3, 'year': u'2018'}, {'value': 0, 'year': u'2014'}, {'value': 0, 'year': u'2017'}]

I want to sort it by year. Can you please help?

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • Maybe the data structure you are using (list of dictionaries) is not adapted to whatever you want to achieve). – Tarik Aug 05 '18 at 17:33
  • @Tarik, I don't think so, it is really doable. See my answer about `itemgetter` – wowkin2 Aug 05 '18 at 17:34

2 Answers2

2

You need to specify the key function applied for comparing when sorting:

my_data = sorted( my_data, key = lambda x : x["year"])
Learning is a mess
  • 7,479
  • 7
  • 35
  • 71
0

You should use itemgetter for that:

>>> from operator import itemgetter
>>> data = [{'value': 2, 'year': u'2015'}, {'value': 4, 'year': u'2016'}, {'value': 3, 'year': u'2018'}, {'value': 0, 'year': u'2014'}, {'value': 0, 'year': u'2017'}]
>>> result = sorted(data, key=itemgetter('year'))
>>> print(result)
[{'value': 0, 'year': '2014'}, {'value': 2, 'year': '2015'}, {'value': 4, 'year': '2016'}, {'value': 0, 'year': '2017'}, {'value': 3, 'year': '2018'}]
wowkin2
  • 5,895
  • 5
  • 23
  • 66