Reputation: 2632
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
?
Upvotes: 9
Views: 6101
Reputation: 2632
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.
Upvotes: 6
Reputation: 309889
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)
Upvotes: 11