嵌套字典的下键,如果下键已存在,则合并数据

2024-04-26 11:13:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个树形结构,从一个嵌套字典中构建而成:

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

我想把它变成:

^{pr2}$

有什么方法可以在python中执行这种转换吗?在

我坚持:一切价值都是字典。在


Tags: 方法testdata字典树形结构other价值
1条回答
网友
1楼 · 发布于 2024-04-26 11:13:11

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

>>> 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': {}}}}

相关问题 更多 >