【问题标题】:Lower keys of nested dictionary and merge data if the lower key already exists [closed]如果下键已经存在,则嵌套字典的下键和合并数据[关闭]
【发布时间】:2013-01-28 02:06:35
【问题描述】:

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

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

我想把它转换成:

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

有没有办法在 python 中执行这种转换?

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

【问题讨论】:

  • 您在哪一部分遇到了问题?
  • 如果下键已经存在则合并字典
  • 见How to merge multiple dicts with same key?...你只需要添加一些小写代码。
  • 试过在 json 上做一个较低的,然后把它转换成字典吗?我不确定这是否可行;我正在使用手机,否则我会自己尝试。
  • 澄清一下:你想合并字典和小写键?

标签: python json dictionary nested


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-05-13
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多