如何在python的深度嵌套字典中对所有列表进行排序?

时间:2019-05-25 12:54:22

标签: python

我想对深度嵌套的字典中的所有列表进行排序。从根本上说,它是一个JSON对象,它将字典深层嵌套在列表中,然后嵌套在字典中。我要做的就是将所有字典键解析到所有叶子节点,并对我在途中遇到的所有列表进行排序。基本上,应该对给定字典对象内直接可用或深入的任何列表进行排序,并应返回具有所有排序列表的同一字典。

我尝试对dict对象进行递归,以将遇到的所有dict对象传递给递归方法,并在遇到时对列表进行排序。但是,当列表中有一个字典,然后该字典对象中有另一个列表时,它们将无法产生结果。

下面的示例JSON:

my_json = {
  a: {
    b: {
      c: [
        {
          d: [
            { f: 'some_string' }
          ]
        },
        {
          e: {
            g: [
              h: 'another string'
            ]
          }
        }
      ]
    }
  }
  z: [
    b: {
      c: [
        {
          d: [
            { f: 'some_string1' }
          ]
        },
        {
          e: {
            g: [
              h: 'another string1'
            ]
          }
        }
      ]
    },
    x: {
      c: [
        {
          d: [
            { f: 'some_string2' }
          ]
        },
        {
          e: {
            g: [
              h: 'another string2'
            ]
          }
        }
      ]
    }
  ]
}
def gen_dict_extract(input_dict):
  result_obj = input_dict;
  if hasattr(var, 'iteritems'):
    for k, v in var.iteritems():
      if isinstance(v, dict):
        for result in gen_dict_extract(v):
          yield result
      elif isinstance(v, list):
        v.sort();
        for d in v:
          for result in gen_dict_extract(d):
            yield result

输出期望只是对所有列表进行排序,无论它们位于何处。我什至可以对字典中的每个项目进行排序,但是列表排序是我所需要的。

在这里举一个较小的示例来解释输出:

old_json = {
    'x': [
        {
            'z': {
                'y': ['agsd', 'xef', 'sdsd', 'erer']
            }
        },
        {
            's': {
                'f': 'ererer',
                'd': [5, 6, 2, 3, 1]
            }
        }
    ]
}

new_json = {
    'x': [
        {
            's': {
                'f': 'ererer',
                'd': [1, 2, 3, 5, 6]
            }
        },
        {
            'z': {
                'y': ['agsd', 'erer', 'sdsd','xef']
            }
        }
    ]
}

Something like above.

2 个答案:

答案 0 :(得分:1)

我相信这里的代码段将完成对嵌套字典的排序。

def nested_sort(d:dict):
    for v in d.values():
        if isinstance(v,dict):
            nested_sort(v)
        elif isinstance(v,list):
            v.sort()

但是,由于您提供的示例不是合法的JSON格式或合法的python字典,因此我无法测试代码。

答案 1 :(得分:0)

如果您希望输出为其他字典(即不对原始字典进行排序),则该函数应这样编写:

def sortedDeep(d):
    if isinstance(d,list):
        return sorted( sortedDeep(v) for v in d )
    if isinstance(d,dict):
        return { k: sortedDeep(d[k]) for k in sorted(d)}
    return d

这样,您可以像使用内置的sorted()函数一样使用sortedDeep():

new_json = sortedDeep(old_json)