Reorder dictionary in pyrhon according to a list of values!!!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • plomon
    New Member
    • Mar 2008
    • 15

    Reorder dictionary in pyrhon according to a list of values!!!

    Let us consider a dictionary:
    Code:
    sample_dict={1:'r099',2:'g444',3:'t555',4:'f444',5:'h666'}
    I want to re-order this dictionary in an order specified by a list containing the order of the dictionary keys that I desire. Let us say the desired order list is:
    Code:
    desired_order_list=[5,2,4,3,1]
    So, I want my dictionary to appear like this:
    Code:
    {5:'h666',2:'g444',4:'f444',3:'t555',1:'r099'}
    How do I achieve this in the least complex way possible?
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    Dictionaries are in hash order always so can not be re-ordered. There is an ordered dictionary object in collections which you might want to use, or you can just use a list of tuples.
    Code:
    sample_dict={1:'r099',2:'g444',3:'t555',4:'f444',5:'h666'}
    output_list = [(key, sample_dict[key]) for key in (5, 4, 2, 1 ,3) if key in sample_dict]
    print output_list

    Comment

    Working...