Reorder dictionary in python according to a list of values

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

    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.

提交回复
热议问题