I am using OrderedDict
to sort a dict
whose keys contain both strings and numbers. Here is my code:
from collections import OrderedDict
x = {}
x['mon'] = 10
x['day_1'] = 1
x['day_2'] = 2
x['day_10'] = 10
x['day_11'] = 11
dictionary1 = OrderedDict(sorted(x.items(), key=lambda t: len(t[0])))
dictionary2 = OrderedDict(sorted(x.items(), key=lambda t: t[0]))
I would like the output looks like (I do not care the location of mon:2
):
OrderedDict([('mon', 2), ('day_1', 1), ('day_2', 2), ('day_10', 10), ('day_11', 11)])
but neither of the method worked. So I guess I might need to customize a sorting rule? Any suggestions?
update:
Here is my combined answer (Simeon Visser and hcwhsa):
def convert_dict_key(key):
try:
return int(key.split('_')[1])
except:
return key
alphanum_key = lambda (key, value): convert_dict_key(key)
dictionary = sorted(dictionary.items(), key=alphanum_key)