How do I sort this list in Python, if my date is in a String?

前端 未结 5 981
一整个雨季
一整个雨季 2020-11-29 08:38
[{\'date\': \'2010-04-01\', \'people\': 1047, \'hits\': 4522}, {\'date\': \'2010-04-03\', \'people\': 617, \'hits\': 2582}, {\'date\': \'2010-04-02\', \'people\': 73         


        
5条回答
  •  感动是毒
    2020-11-29 09:11

    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}]
    

提交回复
热议问题