I have a dictionary and I have sorted that dictionary by values. Following is code with sample data:
mydict = {'b':4, 'a':1, 'd':8, 'c':10}
Now, I want to sort this by value in descending order and hence, I used the following code:
sorted_dict = sorted(mydict.iteritems(), key = operator.itemgetter(1), reverse = True)
When I print sorted_dict, I get a list of tuples:
sorted_dict
[('c', 10), ('d', 8), ('b', 4), ('a', 1)]
However, I want this in the form of dictionary. So I used the following code:
dict(sorted_dict)
and got the following result:
{'a': 1, 'c': 10, 'b': 4, 'd': 8}
So, it looks like dict() method is automatically sorting dictionary by key. However, my desired output is:
{'c':10, 'd':8, 'b':4, 'a':1}
How do I obtain this output?
Can someone please help?