【问题标题】:How to sort all lists in a deeply nested dictionary in python?如何在python中对深度嵌套字典中的所有列表进行排序?
【发布时间】:2019-05-25 12:54:21
【问题描述】:

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

我尝试对 dict 对象进行递归,以将遇到的任何 dict 对象传递给递归方法,并在遇到时对列表进行排序。但是,当列表中有一个 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.

【问题讨论】:

  • 请给minimal reproducible example 说明您尝试过的内容以及具体问题。
  • 我知道您已经非常努力地解释了您正在寻找的输出,但我仍然不明白。您能否更新您的帖子,包括示例 JSON 将被显式转换为的内容?请在问题中!
  • 请添加您的预期输出。这将帮助我们轻松解决您的问题。
  • 完成.. 请看一下。请忽略我的代码,因为它可能无法满足我正在寻找的确切目的。
  • 请重新访问您的输入数据。好像有一些语法错误

标签: python


【解决方案1】:

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

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)

[EDIT] 改进的版本,它还将根据嵌入对象的最小键/值对字典列表(或列表列表)进行排序:

def sortedDeep(d):
    def makeTuple(v): return (*v,) if isinstance(v,(list,dict)) else (v,)
    if isinstance(d,list):
        return sorted( map(sortedDeep,d) ,key=makeTuple )
    if isinstance(d,dict):
        return { k: sortedDeep(d[k]) for k in sorted(d)}
    return d

【讨论】:

  • 这适用于没有重复键的字典。当我们必须使用重复键对字典进行排序时怎么样?
  • 不确定您所说的带有重复键的字典是什么意思。根据定义,字典中的键是唯一的。
  • 对不起,我的意思是 JSON。当 JSON 有重复键时如何进行深度排序?并且可以是list的json列表等等。
  • 我认为 JSON 也不支持字典中的重复键。但是,如果您的问题与“字典列表”(或 JSON 白话中的对象列表)有关,则它不会按原样工作。我添加了一个改进版本,它将根据列表中每个字典的最小键来完成。
  • 我有一个类似这样的有效载荷:ls = {'payload': [{'a': {'aa': [{'aa12': {'aaa23': 230, 'aaa21': 210}}, {'aa11': {'aaa12': 120, 'aaa11': 110}}, {'aa13': {'aaa35': 350, 'aaa32': 320}}], 'ac': ['ac3', 'ac1', 'ac2'], 'aa': [{'aa12': {'aaa22': 22, 'aaa21': 21}}, {'aa01': {'aaa03': 03, 'aaa01': 01}}, {'aa13': {'aaa33': 33, 'aaa32': 32}}, {'aa1': 'aab'}], 'ac': ['ac3', 'ac1', 'ac2']}}, {'b': {'bb': ['bb4', 'bb2', 'bb3', 'bb1']}}]}。我该如何排序?使用上面的代码,它仍然在删除重复的键。
【解决方案2】:

我相信这里的代码 sn-p 将完成对嵌套字典进行排序的工作。

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 字典。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-22
    • 2021-11-01
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    • 2018-10-20
    • 2013-01-21
    • 2021-12-21
    相关资源
    最近更新 更多