python - 嵌套字典的下键和合并数据(如果下键已经存在)

标签 python json dictionary nested

<分区>

我有一个树结构,由嵌套字典构建:

{
  'test': {
    'Data': {},
  },
  'Test': {
    'data': {
      'Other': {},
    },
  },
}

我想将其转换为:

{
  'test': {
    'data': {
      'other': {},
    },
  },
}

有什么方法可以在 python 中执行此转换?

我坚持:所有的值都是字典。

最佳答案

尝试递归函数调用以小写键:

>>> def lower_keys(tree):
        if not tree:
            return tree
        return {k.lower() : lower_keys(v) for k, v in tree.items()}

>>> t = {
  'test': {
    'Data': {},
  },
  'Test': {
    'data': {
      'Other': {},
    },
  },
}

>>> lower_keys(t)
{'test': {'data': {'other': {}}}}

关于python - 嵌套字典的下键和合并数据(如果下键已经存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14554492/

相关文章:

python - 在 Python 中处理异常堆栈跟踪的正确方法

python - 在异步程序中将 Web 响应写入文件

python - 在用 celery beat 安排任务时防止口是心非

jquery - 如何从文件中获取 json 数据(jQuery)

python - 从带有具有列表值的键的字典创建一个新的字典列表

vim - 在 Vim 中阻止注释然后取消突出显示

python - 我可以在 y 系列中输入一个值以防止 matplotlib 绘制该 x 值的值吗?

jquery - 使用 JQuery 检索 JSON 数据后 Html 表单元素消失

json - Jersey 在 Spring 中实现 ContextResolver<JAXBContext>

java - 如何在 Guava 中将expireAfterAccess与CacheBuilder一起使用