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
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.