【问题标题】:Python: Replace keys in a nested dictionaryPython:替换嵌套字典中的键
【发布时间】:2016-11-24 06:48:50
【问题描述】:

我有一个嵌套字典 {1: {2: {3: None}}} 和一个将嵌套字典的键映射到一组值的字典,例如 {1: x, 2: y, 3: z}。我想将嵌套字典转换为这种形式{x: {y: {z: None}}}。我尝试了几个递归函数,但我一直在兜圈子,让自己感到困惑。实现这一目标的最佳方法是什么?

编辑:我忘了提到嵌套级别是任意的。以上是一个简单的例子。

【问题讨论】:

  • 你有现有的代码吗?

标签: python dictionary recursion nested


【解决方案1】:

接受的答案将不支持列表的字典,添加完整的功能

@bilentor,

od = {'name': 'John', '1': [{'name': 'innername'}]}
kd = { 'name': 'cname', '1': '2', 3: 'z' }

def replace_keys(data_dict, key_dict):
    new_dict = { }
    if isinstance(data_dict, list):
        dict_value_list = list()
        for inner_dict in data_dict:
            dict_value_list.append(replace_keys(inner_dict, key_dict))
        return dict_value_list
    else:
        for key in data_dict.keys():
            value = data_dict[key]
            new_key = key_dict.get(key, key)
            if isinstance(value, dict) or isinstance(value, list):
                new_dict[new_key] = replace_keys(value, key_dict)
            else:
                new_dict[new_key] = value
        return new_dict
    return new_dict

nd = replace_keys(od, kd)
print(nd)

【讨论】:

    【解决方案2】:

    您需要在使用新键构建新字典时递归字典。请注意,如果您在某个地方有一个列表或元组,其中有其他字典,它们将不会被处理 - 您必须添加一些代码才能做到这一点。您实际上可以在不构建新字典的情况下做到这一点,但我认为这种方式更简单。

    od = { 1: { 2: { 3: None }}}
    kd = { 1: 'x', 2: 'y', 3: 'z' }
    
    def replace_keys(old_dict, key_dict):
        new_dict = { }
        for key in old_dict.keys():
            new_key = key_dict.get(key, key)
            if isinstance(old_dict[key], dict):
                new_dict[new_key] = replace_keys(old_dict[key], key_dict)
            else:
                new_dict[new_key] = old_dict[key]
        return new_dict
    
    nd = replace_keys(od, kd)
    print nd
    

    输出:

    {'x': {'y': {'z': None}}}
    

    【讨论】:

      猜你喜欢
      • 2023-01-23
      • 2012-07-26
      • 2019-09-06
      • 1970-01-01
      • 2022-10-13
      • 2014-03-30
      • 1970-01-01
      • 2019-01-25
      • 2021-05-10
      相关资源
      最近更新 更多