Reorder dictionary in python according to a list of values

后端 未结 6 1152
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-12 04:27

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

6条回答
  •  星月不相逢
    2021-01-12 04:54

    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.

提交回复
热议问题