0

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)
Community
  • 1
  • 1
TTT
  • 4,354
  • 13
  • 73
  • 123

1 Answers1

3

You can do:

>>> dictionary3 = OrderedDict(sorted(x.items(), key=lambda (key, value): int(key.split('_')[1])))
>>> dictionary3
OrderedDict([('day_1', 1), ('day_2', 2), ('day_10', 10), ('day_11', 11)])

This splits the keys by '_' and sorts the day numbers as integers.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180