Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort OrderedDict using a sorted list of keys?

Tags:

python

sorting

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?

like image 809
kiri Avatar asked May 10 '14 22:05

kiri


People also ask

Can you sort an OrderedDict?

OrderedDict is a sub class of dictionary which remembers the order of entries added in dictionary object. When iterating over an ordered dictionary, the items are returned in the order their keys were first added. We also need to us sorted() function that sorts elements in an iterable in a specified order.

How do I sort by OrderedDict in Python?

To sort a dictionary by value in Python you can use the sorted() function. Python's sorted() function can be used to sort dictionaries by key, which allows for a custom sorting method. sorted() takes three arguments: object, key, and reverse . Dictionaries are unordered data structures.

How do I sort a list of dictionaries by key?

To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.

Can we sort a dictionary with keys?

Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.


1 Answers

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.

like image 199
kiri Avatar answered Sep 18 '22 13:09

kiri