python递归排序所有嵌套的iterable

时间:2018-05-29 23:04:13

标签: python json recursion iterable

如何以可迭代的方式递归排序所有嵌套的iterable?

e.g。

d = {
    'e': [{'y': 'y'}, {'x': [{'2': 2, '1': 1}]}],
    'x': ['c', 'b', 'a'],
    'z': {
        'a': [3, 1, 2],
        'd': [{'y': [6,5,1]}, {'w': 1}],
        'c': {'2': 2, '3': 3, '4': 4}
    },
    'w': {1:1, 2:2, 3:3}
}

我的输出就像

{'e': [{'x': [{'1': 1, '2': 2}]}, {'y': 'y'}],
 'w': {1: 1, 2: 2, 3: 3},
 'x': ['a', 'b', 'c'],
 'z': {'a': [1, 2, 3],
       'c': {'2': 2, '3': 3, '4': 4},
       'd': [{'w': 1}, {'y': [1, 5, 6]}]}}

2 个答案:

答案 0 :(得分:2)

from pprint import pprint
d = {
    'e': [{'y': 'y'}, {'x': [{'2': 2, '1': 1}]}],
    'x': ['c', 'b', 'a'],
    'z': {
        'a': [3, 1, 2],
        'd': [{'y': [6,5,1]}, {'w': 1}],
        'c': {'2': 2, '3': 3, '4': 4}
    },
    'w': {1:1, 2:2, 3:3}
}
def rec_sort(iterable):
    """Recursively sort
    """
    def sort_dict_key(x):
        if isinstance(x, dict):
            return sorted(x.keys(), key=sort_dict_key)
        return x
    if isinstance(iterable, dict):
        d = {}
        for k, v in iterable.items():
            d[k] = rec_sort(v)
    elif isinstance(iterable, list):
        iterable.sort(key=sort_dict_key)
        for pos,item in enumerate(iterable):
            iterable[pos] = rec_sort(item)
    return iterable

pprint(rec_sort(d))

答案 1 :(得分:-1)

您可以使用递归:

import json
d = {'x': ['c', 'b', 'a'], 'z': {'a': [3, 1, 2], 'c': {'3': 3, '2': 2, '4': 4}, 'd': [{'y': [6, 5, 1]}, {'w': 1}]}, 'e': [{'y': 'y'}, {'x': [{'1': 1, '2': 2}]}], 'w': {1: 1, 2: 2, 3: 3}}
def sort_nested(c):
   if not isinstance(c, dict):
     return sorted(c) if isinstance(c, list) else c
   return {a:sorted(sort_nested(i) for i in b) if isinstance(b, list) else sort_nested(b) for a, b in c.items()}

print(json.dumps(sort_nested(d), indent=4))

输出:

{
 "x": [
    "a", 
    "b", 
    "c"
], 
"z": {
    "a": [
        1, 
        2, 
        3
    ], 
    "c": {
        "3": 3, 
        "2": 2, 
        "4": 4
    }, 
    "d": [
        {
            "w": 1
        }, 
        {
            "y": [
                1, 
                5, 
                6
            ]
        }
    ]
}, 
"e": [
    {
        "x": [
            {
                "1": 1, 
                "2": 2
            }
        ]
    }, 
    {
        "y": "y"
    }
 ], 
  "w": {
    "1": 1, 
    "2": 2, 
    "3": 3
   }
}