Reorder dictionary in python according to a list of values

后端 未结 6 1150
爱一瞬间的悲伤
爱一瞬间的悲伤 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:40

    Using an OrderedDict or Eli's solution will probably be a good way to go, but for reference here is a simple way to obtain the list of values you want:

    [sample_dict[k] for k in desired_order_list]
    

    If you aren't completely sure that every element from desired_order_list will be a key in sample_dict, use either [sample_dict.get(k) ...] or [... for k in desired_order_list if k in sample_dict]. The first method will put None in for missing keys, the second method will only include values from the keys are are in the dict.

提交回复
热议问题