By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,922 Members | 1,689 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,922 IT Pros & Developers. It's quick & easy.

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

P: 15
Let us consider a dictionary:
Expand|Select|Wrap|Line Numbers
  1. sample_dict={1:'r099',2:'g444',3:'t555',4:'f444',5:'h666'}
  2.  
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:
Expand|Select|Wrap|Line Numbers
  1. desired_order_list=[5,2,4,3,1]
So, I want my dictionary to appear like this:
Expand|Select|Wrap|Line Numbers
  1. {5:'h666',2:'g444',4:'f444',3:'t555',1:'r099'}
How do I achieve this in the least complex way possible?
May 8 '11 #1
Share this Question
Share on Google+
1 Reply


Expert 100+
P: 624
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.
Expand|Select|Wrap|Line Numbers
  1. sample_dict={1:'r099',2:'g444',3:'t555',4:'f444',5:'h666'}
  2. output_list = [(key, sample_dict[key]) for key in (5, 4, 2, 1 ,3) if key in sample_dict]
  3. print output_list 
May 8 '11 #2

Post your reply

Sign in to post your reply or Sign up for a free account.