0

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?

user3694373
  • 140
  • 1
  • 9

1 Answers1

4

You can’t with a regular dict, which is not an ordered collection to begin with. collections.OrderedDict, however, is!

>>> from collections import OrderedDict
>>> d = OrderedDict([('c', 10), ('d', 8), ('b', 4), ('a', 1)])
>>> d
OrderedDict([('c', 10), ('d', 8), ('b', 4), ('a', 1)])

Granted, the output doesn’t look very meaningful, but it is correct. You can access items by key and iterate through pairs in order.

Ry-
  • 218,210
  • 55
  • 464
  • 476