Python full order nested dict

I have a kind of trie consisting of OrderedDicts (but in the wrong order) that looks like this:

    test = {
        'ab':{
            '1':{},
            '2':{
                '002':{},
                '001':{}}},
        'aa':{
            '02':{
                'ac':{},
                '01':{}, 
                'ca':{}, 
                'ab':{}},
            '01':{
                'b':{}, 
                'z':{
                    '0':{}, 
                    '1':{}}}}
    }

How can I get the full order of this dict at all subsequent levels?

If I use collections.OrderedDict (sorted (test.iteritems ())) , I only sort it for the first level.

I feel that I need to create a function that somehow calls itself recursively to the deepest level, but after I spent many hours on various ways to solve the problem, I'm still stuck here.

In the end, it should look like this:

    test = {
        'aa':{
            '01':{
                'b':{}, 
                'z':{
                    '0':{}, 
                    '1':{}}},
            '02':{
                '01':{},
                'ab':{},
                'ac':{},
                'ca':{}}},

        'ab':{
            '1':{},
            '2':{
                '001':{},
                '002':{}}}
    }
+4
source share
3

, : . .

def make_ordered(d):
    if isinstance(d, dict):
        return OrderedDict(sorted((key, make_ordered(value)) for key, value in d.iteritems()))
    else:
        return d
+3

, blist package. , sorteddict. .

sorteddict docs . - BSD, .

+1
from collections import OrderedDict as OD
def order(X):
    retval = OD()

    # The standard iterator of a dict is its keys.
    for k in sorted(X):
        # Incase it something we can't handle.
        if isinstance(X[k], dict):
            # I want my children dicts in order.
            retval[k] = order(X[k])
        else:
            retval[k] = X[k]

    return retval
+1
source

Source: https://habr.com/ru/post/1528804/


All Articles