Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reorder a python ordered dict based on array?

Tags:

python

Say I have an Ordered Dict with the following items:

mydict = {'Rust': {'definition':'rusts definition'}, 'Iron': {'definition:'iron definition'}, 'Pyrite': {'definition':'pyrite definition'}}

If I have an array:

myorder = ['Pyrite', 'Rust', 'Iron']

How can I reorder the Ordered Dict such that the items in mydict are ordered based on myorder?

like image 268
Rolando Avatar asked Aug 23 '13 14:08

Rolando


1 Answers

Try this:

mydict = {'Rust': {'definition':'rusts definition'},
          'Iron': {'definition':'iron definition'},
          'Pyrite': {'definition':'pyrite definition'}}

myorder = ['Pyrite', 'Rust', 'Iron']

from collections import OrderedDict

ordered = OrderedDict()
for k in myorder:
    ordered[k] = mydict[k]

Or even shorter:

ordered = OrderedDict((k, mydict[k]) for k in myorder)

Using the above snippet, ordered will contain the same keys/values as mydict, but they'll be inserted in the same order specified by myorder. That's the advantage of OrderedDict: when iterating over it, it'll preserve the insertion order.

There's no way to sort the existing dictionary in-place (well, you could extract all the key-value pairs, eliminate them and add them again in the correct order, but that's not the idea, is it?), it's necessary to create a new one ... or simply iterate over the existing dictionary in the specified order:

for k in myorder:
    x = mydict[k] # do something with x
like image 77
Óscar López Avatar answered Oct 09 '22 06:10

Óscar López