Mike Hatcher
Mike Hatcher

Reputation: 21

Python sorting nested dictionary list

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!

Upvotes: 2

Views: 450

Answers (1)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52153

>>> 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())

Upvotes: 1

Related Questions