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

后端 未结 5 1764
攒了一身酷
攒了一身酷 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:39

    If you install my blist package, it includes a sorteddict type. Then you could simply:

    from blist import sorteddict
    
    def my_key(dict_key):
           try:
                  return int(dict_key)
           except ValueError:
                  return dict_key
    
    a = {'100':12,'6':5,'88':3,'test':34, '67':7,'1':64 }
    print sorteddict(my_key, **a).keys()
    

    Output:

    ['1', '6', '67', '88', '100', 'test']
    

提交回复
热议问题