Let us consider a dictionary:
sample_dict={1:'r099',2:'g444',3:'t555',4:'f444',5:'h666'}
I want to re-order this dictionary in an order specified by a list containing the order of the dictionary keys that I desire. Let us say the desired order list is:
desired_order_list=[5,2,4,3,1]
So, I want my dictionary to appear like this:
{5:'h666',2:'g444',4:'f444',3:'t555',1:'r099'}
If I can get a list of values that is fine too. Meaning, the result can be this:
['h666','g444','f444','t555','r099']
How do I achieve this in the least complex way possible?
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.
Sort Dictionary Using a for Loop We can sort a dictionary with the help of a for loop. First, we use the sorted() function to order the values of the dictionary. We then loop through the sorted values, finding the keys for each value. We add these keys-value pairs in the sorted order into a new dictionary.
We can sort lists, tuples, strings, and other iterable objects in python since they are all ordered objects. Well, as of python 3.7, dictionaries remember the order of items inserted as well. Thus we are also able to sort dictionaries using python's built-in sorted() function.
Use dict. items() to get a list of tuple pairs from d and sort it using a lambda function and sorted(). Use dict() to convert the sorted list back to a dictionary. Use the reverse parameter in sorted() to sort the dictionary in reverse order, based on the second argument.
Answer for Python 3.6+
Guido has assured dictionaries would be ordered from Python 3.7 onwards, and they already were as an experimental feature in 3.6. The answer has already been expanded on in Fastest way to sort a python 3.7+ dictionary.
In this case, building a new dict with simple dictionary comprehension based on the items contained in the desired_order_list
will do the trick.
sample_dict = {1: 'r099', 2: 'g444', 3: 't555', 4: 'f444', 5: 'h666'}
print(sample_dict)
>>> {1: 'r099', 2: 'g444', 3: 't555', 4: 'f444', 5: 'h666'}
desired_order_list = [5, 2, 4, 3, 1]
reordered_dict = {k: sample_dict[k] for k in desired_order_list}
print(reordered_dict)
>>> {5: 'h666', 2: 'g444', 4: 'f444', 3: 't555', 1: 'r099'}
If you're using an OrderedDict
, you can do
for key in [5,2,4,3,1]:
my_ordered_dict[key] = my_ordered_dict.pop(key)
This reinserts everything in your ordered dict in the sequence you want, such that later you can do
my_ordered_dict.values()
And get the list you suggested in the question.
If you wrap the reinsertion in a try: ...; except KeyError: pass
, you can reorder an OrderedDict
even if not all the keys in your list are present.
Python dictionaries are unordered.
Use OrderedDict instead.
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