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
?
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.
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.
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.
Dictionaries are made up of key: value pairs. Thus, they can be sorted by the keys or by the values.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With