-11

In python, how do I quick sort a nested dictionary into an OrderedDict? For example:

{'susan': {'number': '5', 'fav_color': 'yellow'},
'josh': {'number': '1', 'fav_color': 'blue'},
'casey': {'number': '11', 'fav_color': 'orange'}}

I want to sort on number such that I end up with:

{'josh': {'number': '1', 'fav_color': 'blue'},
'susan': {'number': '5', 'fav_color': 'yellow'},
'casey': {'number': '11', 'fav_color': 'orange'}}
babyDev
  • 415
  • 5
  • 8
  • so.... Did you try anything? – roganjosh Apr 09 '18 at 22:46
  • 2
    Why do you want to quicksort instead of just using the normal timsort? – abarnert Apr 09 '18 at 22:47
  • Can you adapt the answers from [this question](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) to suit your needs? – Aran-Fey Apr 09 '18 at 22:47
  • 1
    But either way, the answer will be similar: instead of a dict comprehension over `sorted(d.items(), key=whatever)` you'd do a dict comprehension over `some_quicksort_function_you_wrote_or_found(d.items(), key=whatever)`. – abarnert Apr 09 '18 at 22:48
  • 1
    This is Yet Another Case of sorting on a particular key -- in this case, it's `int(elem['number'])`. There are myriad tutorials and examples on line. Exactly where are you stuck? – Prune Apr 09 '18 at 22:49

1 Answers1

2

You can't resort the OrderedDict in place. If you check out the source for the collections.OrderedDict, the sort order is stored in a linked list, which is a "private" double-underscore variable that you can't change.

You can, however, sort the iterated key and values and create a new OrderedDict based on your sort preference

OrderedDict(sorted(d.items(), key=lambda x: int(x[1]['number'])))
Brendan Abel
  • 35,343
  • 14
  • 88
  • 118
  • @Aran-Fey Ah, righto, didn't even notice they were strings. – Brendan Abel Apr 09 '18 at 23:00
  • This worked thank you – babyDev Apr 09 '18 at 23:05
  • These days, the `OrderedDict` implementation in `collections/__init__.py` isn't even used; it's replaced by the C implementation in [`odictobject.c`](https://github.com/python/cpython/blob/3.6/Objects/odictobject.c), where the ordering information is even harder to screw with from outside. – user2357112 Apr 09 '18 at 23:06