1

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)
5
  • 1
    This is called a 'natural sort' Commented Nov 12, 2013 at 18:46
  • 1
    Dup: Does Python have a built in function for string natural sort? Commented Nov 12, 2013 at 18:46
  • @hcwhsa: Sort of. But that post does not have the solution using OrderDict Commented Nov 12, 2013 at 18:51
  • @tao.hong You're sorting a list here(x.items()) not OrderedDict. Commented Nov 12, 2013 at 18:52
  • @Thanks for pointing that out. I do get an idea from that post. Commented Nov 12, 2013 at 18:57

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.