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
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)