Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing sorted dictionary in Python 3

I'm sorting my dictionary by key, but I'd like to reverse the order. However I'm not getting much joy with a few of the examples I have seen around the web.

Here is the sort

tempdict = collections.OrderedDict(sorted(tempdict.items()))

now I'm trying:

reverse = collections.OrderedDict(tempdict.items()[::-1])
reverse = collections.OrderedDict(map(reversed, tempdict.items()))

But these are not working. What is the smartest and most elegant way of sorting the dictionary. Yes I know, dictionaries are not really used for the sorting, but this works well for us. Thanks.

like image 476
disruptive Avatar asked Apr 01 '13 12:04

disruptive


1 Answers

To sort in reverse order:

collections.OrderedDict(sorted(tempdict.items(), reverse=True))

To reverse an existing dict:

collections.OrderedDict(reversed(list(tempdict.items())))
like image 137
Pavel Anossov Avatar answered Sep 16 '22 14:09

Pavel Anossov