How to sort a dictionary having keys as a string of numbers in Python

后端 未结 5 1737
攒了一身酷
攒了一身酷 2020-12-10 05:04

I have a dictionary:

a = {\'100\':12,\'6\':5,\'88\':3,\'test\':34, \'67\':7,\'1\':64 }

I want to sort this dictionary with respect to key s

5条回答
  •  一整个雨季
    2020-12-10 05:46

    You cannot sort a dict in Python as the dict type is inherently unordered. What you can do is sort the items before you used them using the sorted() built in function. You will also need a helper function to distinguish between your numerical and string keys:

    def get_key(key):
        try:
            return int(key)
        except ValueError:
            return key
    a = {'100':12,'6':5,'88':3,'test':34, '67':7,'1':64 }
    print sorted(a.items(), key=lambda t: get_key(t[0]))
    

    However in Python 3.1 (and 2.7) the collections module contains the collections.OrderedDicttype that can be used to achieve the effect you want like below:

    def get_key(key):
        try:
            return int(key)
        except ValueError:
            return key
    a = {'100':12,'6':5,'88':3,'test':34, '67':7,'1':64 }
    b = collections.OrderedDict(sorted(a.items(), key=lambda t: get_key(t[0])))
    print(b)
    

提交回复
热议问题