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!

4
  • 2
    collections.OrderedDict(sorted({'Key3':4,'Key2':3,'Key4':2,'Key1':1}.items())) Commented Sep 9, 2016 at 3:37
  • dicts are unordered. like the comment above look at OrderedDict more here: stackoverflow.com/questions/526125/… Commented Sep 9, 2016 at 3:40
  • Why do you need the dictionaries sorted? Commented Sep 9, 2016 at 3:43
  • #python3.6 news: OrderedDict is dead. Long live dicts that are ordered. Regular dicts are ordered and more compact: bugs.python.org/issue27350 Commented Sep 9, 2016 at 4:02

1 Answer 1

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())
Sign up to request clarification or add additional context in comments.

3 Comments

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);
@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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.