Sort nested dict in python – OrderedDict

Nested ordered dict sort. If you need to sort your dict or OrderedDict, this snippet may come helpfull.

from collections import OrderedDict
def ordered_dict(od, reverse=False, sort_key=None):
    """Sort nested ordered dict recursively.

    sort_key
    - sort by dict key case insensitively:
        sort_key = lambda (k, v): k.lower()
    """
    if not isinstance(od, OrderedDict):
        od = OrderedDict(od)

    res = OrderedDict()
    for k, v in sorted(od.items(), reverse=reverse, key=sort_key):
        if isinstance(v, dict):
            res[k] = ordered_dict(v)
        else:
            res[k] = v
    return res

# show-off
a = {chr(i+ord('a')+(i%2)*(ord('A')-ord('a'))): i for i in reversed(range(0,26))}
print(ordered_dict(a, reverse=True, sort_key=lambda (k,v): k.lower()))

Napsat komentář

Vaše emailová adresa nebude zveřejněna. Vyžadované informace jsou označeny *