2

I am trying to sort a nested dictionary in Python.

Right now I have a dictionary of dictionaries. I was able to sort the outer keys using sorted on the list before I started building the dictionary, but I am unable to get the inner keys sorted at same time.

I've been trying to mess with the sorted API whereas still having problems with it.

Right now I have:

myDict = {'A': {'Key3':4,'Key2':3,'Key4':2,'Key1':1},
          'B': {'Key4':1,'Key3':2,'Key2':3,'Key1':4},
          'C': {'Key1':4,'Key2':2,'Key4':1,'Key3':3}};

But I would like:

myDict = {'A': {'Key1':1,'Key2':3,'Key3':4,'Key4':2},
          'B': {'Key1':4,'Key2':3,'Key2':1,'Key4':1},
          'C': {'Key1':4,'Key2':2,'Key3':3,'Key4':1}};

I appreciate the help!

cezar
  • 11,616
  • 6
  • 48
  • 84
  • 2
    `collections.OrderedDict(sorted({'Key3':4,'Key2':3,'Key4':2,'Key1':1}.items()))` – Ozgur Vatansever Sep 09 '16 at 03:37
  • dicts are unordered. like the comment above look at OrderedDict more here: http://stackoverflow.com/questions/526125/why-is-python-ordering-my-dictionary-like-so – GMarsh Sep 09 '16 at 03:40
  • Why do you need the dictionaries sorted? – wwii Sep 09 '16 at 03:43
  • #python3.6 news: OrderedDict is dead. Long live dicts that are ordered. Regular dicts are ordered and more compact: http://bugs.python.org/issue27350 – Paul Rooney Sep 09 '16 at 04:02

1 Answers1

1
>>> from collections import OrderedDict

>>> def sortedDict(items):
...     return OrderedDict(sorted(items))

>>> myDict = {'A': {'Key3':4,'Key2':3,'Key4':2,'Key1':1},
...           'B': {'Key4':1,'Key3':2,'Key2':3,'Key1':4},
...           'C': {'Key1':4,'Key2':2,'Key4':1,'Key3':3}}

>>> sortedDict((key, sortedDict(value.items())) for key, value in myDict.items())
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
  • Am I forced to use OrderedDict? I was thinking I could iterate through myDict keys and somehow order the inner dictionary using something like sorted(myDict[k].items(), key=lambda x: x[0], reverse=False); – Mike Hatcher Sep 09 '16 at 04:10
  • @MikeHatcher dictionaries are unordered collections. If you apply `sorted` on a dictionary like you said, then it returns an array of sorted tuples. Once you call `dict(sorted(..))` on array to convert it to a dict, it will become unordered again. Thus, you must use `OrderedDict`. – Ozgur Vatansever Sep 09 '16 at 04:20
  • 1
    Ah okay so I guess I'm going to have to generate it a different way then I have been, so I can print in the order that I want. – Mike Hatcher Sep 09 '16 at 04:22