Reorder dictionary in python according to a list of values

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

    Answer for Python 3.6+

    Guido has assured dictionaries would be ordered from Python 3.7 onwards, and they already were as an experimental feature in 3.6. The answer has already been expanded on in Fastest way to sort a python 3.7+ dictionary.

    In this case, building a new dict with simple dictionary comprehension based on the items contained in the desired_order_list will do the trick.

    sample_dict = {1: 'r099', 2: 'g444', 3: 't555', 4: 'f444', 5: 'h666'}
    print(sample_dict)
    >>> {1: 'r099', 2: 'g444', 3: 't555', 4: 'f444', 5: 'h666'}
    
    desired_order_list = [5, 2, 4, 3, 1]
    
    reordered_dict = {k: sample_dict[k] for k in desired_order_list}
    print(reordered_dict)
    >>> {5: 'h666', 2: 'g444', 4: 'f444', 3: 't555', 1: 'r099'}
    

提交回复
热议问题