9

Suppose I have a collections.OrderedDict object and a re-arranged list of its keys:

ordereddict = collections.OrderedDict((
    ('key_78', 'value'),
    ('key_40', 'value'),
    ('key_96', 'value'),
    ('key_53', 'value'),
    ('key_04', 'value'),
    ('key_89', 'value'),
    ('key_52', 'value'),
    ('key_86', 'value'),
    ('key_16', 'value'),
    ('key_63', 'value'),
))

# Example only; actual list will **not** == sorted(ordereddict)
key_list = ['key_04', 'key_16', 'key_40', 'key_52', 'key_53', 'key_63', 'key_78', 'key_86', 'key_89', 'key_96']

How can I sort the OrderedDict so that it is ordered in the same way as the key_list?

2
  • Is there any reason to avoid creating a new ordereddict? Because that's easy ...
    – mgilson
    May 10, 2014 at 23:08
  • why do you want a list of keys to sort the keys, why not just sort the keys themselves? May 11, 2014 at 2:08

2 Answers 2

11

Just create a new OrderedDict:

newdct = OrderedDict((key, olddct[key]) for key in sortedlist)

If you really need this to happen in place, you can clear the olddct and update it with the new one:

olddct.clear()
olddct.update(newdct)
4
  • I tested the performance (with timeit), and my method was 2-4 times faster. Apart from that, modifying the dict in place is also more suited to its use in my program.
    – kiri
    May 10, 2014 at 23:23
  • @minerz029 Your method requires Python 3, though. May 11, 2014 at 7:06
  • @user4815162342: I'm using Python 3.3, but I'll add a note to my answer.
    – kiri
    May 11, 2014 at 7:46
  • 1
    @minerz029 -- Also, what exactly did you time? Did you time just creating a new dict or also clearing the old and updating it? In general, you probably don't need do steps 2 and 3 and I would argue that the code is more clear which is worth spending a few extra microseconds on :-)
    – mgilson
    May 11, 2014 at 20:29
6

Use the following:

def sort_by_list(dict_, list_):
    for key in list_:
        dict_.move_to_end(key)

sort_by_list(ordereddict, key_list)

This only works if the list_ contains all the keys in the dict, and on Python 3.2 or later.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.