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
What is the meaning of reordering the dictionary for you? Dictionaries are unordered data structures by their nature - they are used for lookup rather than order.
Do you want to iterate over the dictionary in some specific order? Then just use your desired_order_list
:
for key in desired_order_list:
# d is the dictionary
# do stuff with d[key]
As others have mentioned, Python has an OrderedDict
(in 2.7 or 3.x), but I don't think it's what you need here. "Reordering" it is just too inefficient. It's much better to just carry your dictionary along with the list of keys in desired order, together.
If you still insist on an OrderedDict
, just create a new OrderedDict
, inserting the value into it in the order of desired_order_list
.