Sorting a nested OrderedDict by key, recursively

python find(key in nested dictionary)
sort nested dictionary by value python
iterate through nested dictionary python
write a python program to sort a list of nested dictionaries
python get all values from nested dictionary
python create nested dictionary recursion
python sort dictionary by value descending
python sort by key

Say orig is an OrderedDict which contains normal string:string key value pairs, but sometimes the value could be another, nested OrderedDict.

I want to sort orig by key, alphabetically (ascending), and do it recursively.


  • Assume key strings are unpredictable
  • Assume nesting can take place infinitely, e.g. level 1-50 all have both strings, OrderedDicts, etc as values.

Need an assist with the sorted algorithm:

import string
from random import choice

orig = OrderedDict((
    ('a', choice(string.digits)),
    ('b', choice(string.digits)),
    ('c', choice(string.digits)),
    ('special', OrderedDict((
        ('a', choice(string.digits)),
        ('b', choice(string.digits)),
        ('c', choice(string.digits)),

sorted_copy = OrderedDict(sorted(orig.iteritems(), ...))

self.assertEqual(orig, sorted_copy)

EDIT: for python 3.6+, @pelson's answer is better

something like:

def sortOD(od):
    res = OrderedDict()
    for k, v in sorted(od.items()):
        if isinstance(v, dict):
            res[k] = sortOD(v)
            res[k] = v
    return res

Python, Sort nested dictionary by key. # using OrderedDict() + sorted(). from collections import OrderedDict. from operator import getitem. # initializing� Sorting has quite vivid applications and sometimes, we might come up with the problem in which we need to sort the nested dictionary by the nested key. This type of application is popular in web development as JSON format is quite popular.

@acushner's solution can now be simplified in python3.6+ as dictionaries now preserve their insertion order.

Given we can now use the standard dictionary, the code now looks like:

def order_dict(dictionary):
    result = {}
    for k, v in sorted(dictionary.items()):
        if isinstance(v, dict):
            result[k] = order_dict(v)
            result[k] = v
    return result

Because we can use standard dictionaries, we can also use standard dictionary comprehensions, so the code boils down to:

def order_dict(dictionary):
    return {k: order_dict(v) if isinstance(v, dict) else v
            for k, v in sorted(dictionary.items())}

See also for detail on python's ordered dictionary implementation. Also, the pronouncement that this will be a language feature as of python 3.7:

Sort Nested Dictionary By Key in Python � GitHub, In order to sort a dictionary by key including nested dictionary inside, we can do: dict, you may add list sorting if you want to sort a nested JSON recursively. Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. Below is an iterative algorithm for insertion sort. Algorithm // Sort an arr[] of size n insertionSort(arr, n) Loop from i = 1 to n-1. a) Pick element arr[i] and insert it into sorted sequence arr[0..i-1]

Very similar to @acushner's solution, but class-based:

from collections import OrderedDict

class SortedDict(OrderedDict):

    def __init__(self, **kwargs):
        super(SortedDict, self).__init__()

        for key, value in sorted(kwargs.items()):
            if isinstance(value, dict):
                self[key] = SortedDict(**value)
                self[key] = value


sorted_dict = SortedDict(**unsorted_dict)

recursively convert nested dicts to nested namedtuples, giving you , Convert mappings to 'tupperwares' recursively. It recursively turns mappings ( dictionaries) into namedtuples. Thus mapping[key] = tupperware(value) def tupleware(obj): if isinstance(obj, dict): fields = sorted(obj.keys()) namedtuple_type � Given a nested dictionary, the task is to convert this dictionary into a flattened dictionary where the key is separated by ‘_’ in case of the nested key to be started. Given below are a few methods to solve the above task.

I faced a very similar issue with getting a stable object so I could get a stable hash, except I had objects with a mix of lists and dictionaries, so I had to sort all the dictionaries, depth first, and then sort the lists. This extends @acushner's answer:

def deep_sort(obj):
    if isinstance(obj, dict):
        obj = OrderedDict(sorted(obj.items()))
        for k, v in obj.items():
            if isinstance(v, dict) or isinstance(v, list):
                obj[k] = deep_sort(v)

    if isinstance(obj, list):
        for i, v in enumerate(obj):
            if isinstance(v, dict) or isinstance(v, list):
                obj[i] = deep_sort(v)
        obj = sorted(obj, key=lambda x: json.dumps(x))

    return obj

As a side point, if you find yourself with classes in your objects that you need to sort, you can jsonpickle.dumps() them, then json.loads() them, then deep_sort() them. If it matters, then you can always json.dumps() and jsonpickle.loads() to get back to where you started, except sorted (well, only sorted in Python 3.6+). For cases of a stable hash, that wouldn't be necessary though.

How to recursively iterate a nested Python dictionary?, Given below is a nested directory objectD1={1: {2: {3: 4, 5: 6}, 3: {4: 5, 6: 7}}, 2: {3: {4: 5}, 4: {6: 7}}}ExampleFollowing recursive function is called repet def iterdict(d): for k,v in d.items(): if isinstance(v, dict): iterdict(v) else: print (k,":",v) object is passed to this function, all the key-value pairs are traversed. The Selection Sort algorithm sorts maintains two parts.. First part that is already sorted; Second part that is yet to be sorted. The algorithm works by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the end of sorted part.

Comparing nested Python dictionaries with no hassle, Comparing nested Python dictionaries with no hassle I searched the web for solutions on how to do that properly, and found a lot of recursive approaches, all trying to The only hurdle is that the dictionary keys need to be sorted, otherwise import jsondict_ = dict(b=1, a=2, z=3, f=4, e=dict(F=1, C=2)) Teams. Q&A for Work. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more

How to loop through all nested dictionary values using a for-loop in , Use recursion to loop through all nested dictionary values Use the syntax for key, value in dict.items to loop over each key, value pair in dict . uses machine learning to provide you with code completions in real time sorted by relevance. I want to convert a dict of audio metadata into an ordered dict, sorted by it's nested values (such as values of keys 'artist' or 'track'). What would be the fastest way to achieve this? The database is organized like this: #!/usr/bin/python3 from

Modifying Deeply-Nested Structures �, Return the same JSON document, but with the points list sorted by stop time lists and dicts), we can start with a recursive function that will walk the structure Note that each step is explicit: it's either a step into a dict key (the� Have another way to solve this solution? Contribute your code (and comments) through Disqus. Previous: Write a Python program to convert list to list of dictionaries. Next: Write a Python program to split a list every Nth element.

  • Is it only a single level deep? Or the OrderedDict corresponding to special could have another OrderedDict inside it?
  • @SukritKalra I added a Rules section to the question that will hopefully lead to a solution that can be repurposed without special knowledge of the OrderedDict structure.
  • @StevenRumbalski needed it for safely creating checksums of dicts that contain lots of different nested data types. Little things like dict key order were altering the checksum, even though the contents of the dict had not technically changed. Sorting these keys before quickly calculating the dict's hash with hashlib.md5(str(my_dict).hexdigest() allowed me to safely compare future versions. (The REAL reason is MongoDB doesn't guarantee object order per: TLDR: ... long story
  • nice. Extra credit if it remains sorted when inserting extra values OR when calling my_sorted_dict.sort()
  • This can be achieved by overriding your iterator of choice (or all of them): def items(self): for key, value in sorted(self.keys()): yield key, value The items in the dictionary will be sorted on read instead of on insert.