How to sort dictionary by key in numerical order Python

后端 未结 4 754
时光取名叫无心
时光取名叫无心 2020-12-01 15:59

Here is the dictionary looks like:

{\'57481\': 50, \'57480\': 89, \'57483\': 110, \'57482\': 18, \'57485\': 82, \'57484\': 40}  

I would

4条回答
  •  一向
    一向 (楼主)
    2020-12-01 16:34

    Standard Python dicts are "unordered". You can use an OrderedDict, take a look at the docs:

    from collections import OrderedDict
    
    d = {'57481': 50, '57480': 89, '57483': 110, '57482': 18, '57485': 82, '57484': 40}
    OrderedDict(sorted(d.items(), key=lambda t: t[0]))
    # OrderedDict([('57480', 89), ('57481', 50), ('57482', 18), ('57483', 110), ('57484', 40), ('57485', 82)])
    

提交回复
热议问题