[{'date': '2010-04-01', 'people': 1047, 'hits': 4522}, {'date': '2010-04-03', 'people': 617, 'hits': 2582}, {'date': '2010-04-02', 'people': 736, 'hits': 3277}]
Suppose I have this list. How do I sort by “date”, which is an item in the dictionary. But, “date” is a string…
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
.sort(key=lambda x: datetime.datetime.strptime(x['date'], '%Y-%m-%d'))
Method 2
Fortunately, ISO format dates, which seems to be what you have here, sort perfectly well as strings! So you need nothing fancy:
import operator
yourlistofdicts.sort(key=operator.itemgetter('date'))
Method 3
Satoru.Logic’s solution is clean and simple. But, per Alex’s post, you don’t need to manipulate the date string to get the sort order right…so lose the .split('-')
This code will suffice:
records.sort(key=lambda x:x['date'])
Method 4
In python 2.6 you can use soerted w/operator.itemgetter.
Since date is YYYY-MM-DD it is sorted even though its a string cause its largest to smallest – i use that format all the time for this reason
>>> import operator
>>> l = [{'date': '2010-04-01','people': 1047, 'hits': 4522},
{'date': '2010-04-03', 'people': 617, 'hits': 2582},
{'date': '2010-04-02', 'people': 736, 'hits': 3277}]
>>> sorted( l, key = operator.itemgetter('date') )
[{'date': '2010-04-01', 'hits': 4522, 'people': 1047}, {'date': '2010-04-02', 'hits': 3277, 'people': 736}, {'date': '2010-04-03', 'hits': 2582, 'people': 617}]
Method 5
records = [
{'date': '2010-04-01', 'people': 1047, 'hits': 4522},
{'date': '2010-04-03', 'people': 617, 'hits': 2582},
{'date': '2010-04-02', 'people': 736, 'hits': 3277}
]
records.sort(key=lambda x: x['date'].split('-'))
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0