>>> from collections import OrderedDict
>>> sorted_dict = OrderedDict()
>>> dct = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> dct.values().sort()
>>> for x in sorted(dct.values(), reverse=True):
... keys = [idx for idx in dct if dct[idx]==x]
... for key in keys:
... sorted_dict[key] = x
...
>>>
>>> sorted_dict
OrderedDict([(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)])
>>>
or if you are dead set on writing something that looks like dict syntax to a file,
>>> def print_dict_looking_thing(ordered_dict):
... print "{"
... for key, value in ordered_dict.iteritems():
... print "{0}: {1},".format(key, value)
... print "}"
...
>>> print_dict_looking_thing(sorted_dict)
{
3: 4,
4: 3,
1: 2,
2: 1,
0: 0,
}
That is how OrderedDict “solves your problem”. But, a few points worth reemphasizing:
- Dicts are unordered. You can’t “sort them”, only operate on their keys and values.
- OrderedDicts remember the order that items were added.
- It sounds like you are trying to print to a file something that looks like dict syntax. If you do that and read the dict into python at some point, it will become an unordered object (a dict) again.
- It is not super clear what “your problem” is. What is the desired end state; printing a string that reads like dict syntax? Making something that has the accessor methods that dicts do? Clarifying what exactly you want (in terms of performance) would be helpful.
- The code above has O(n**2) complexity. Don’t use it on big things.
0
solved List to dict: incorrectly sorted result