如何在深度嵌套的字典中出现所选键的任何位置用其值替换键:值对? [英] How can I replace a key:value pair by its value wherever the chosen key occurs in a deeply nested dictionary?

查看:23
本文介绍了如何在深度嵌套的字典中出现所选键的任何位置用其值替换键:值对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是如何用来自同一键值对的值替换嵌套字典中的键值对? 答案仅适用于一次性嵌套的字典.它是遍历所有嵌套字典值? 我无法解决这个问题.

This is a spin-off from How can I replace a key-value pair in a nested dictionary with the value from the same key-value pair? where the answer is working only in a one-time-nested dictionary. And it is a spin-off from Loop through all nested dictionary values? which I could not get to work on this problem.

我有一本嵌套多次的字典.

I have a dictionary that is nested many times.

dict_nested = {
    "key_":{
        "key0a":{
            "key1a":{
                "sub_key2a":"sub_value2a",
                "sub_key2b":"sub_value2b"},
            "key1b":"value1b"},
        "key0b":{
            "key_XYZ":{
                "key1a":{
                    "sub_key2a":"sub_value2a",
                    "sub_key2b":"sub_value2b"},
                "key1b":"value1b"}
            }
        }
    }

之后:

结果应该是这样的:

After:

The result should look like this:

dict_nested_new = {
    "key_":{
        "key0a":{
            "sub_key2a":"sub_value2a",
            "sub_key2b":"sub_value2b",
            "key1b":"value1b"},
        "key0b":{
            "key_XYZ":{
                "sub_key2a":"sub_value2a",
                "sub_key2b":"sub_value2b",
                "key1b":"value1b"}
            }
        }
    }

在迭代时修改 Python dict

当我遍历字典的项目以删除/替换时,出现错误

Modifying a Python dict while iterating over it

When I looped through the items of the dictionary to delete / replace, I got the error

RuntimeError: 字典在迭代过程中改变了大小

RuntimeError: dictionary changed size during iteration

需要以某种方式避免.

如何在 "key1a":SOME_VALUE 键值对每次出现在字典中的某个位置时用它的值替换它?

How can I replace the "key1a":SOME_VALUE key-value pair with its value each time it occurs somewhere in the dictionary?

推荐答案

据我所知,您希望在嵌套的 dict 中递归搜索键并提升其值.

As I understand it, you want to recursively search for a key in a nested dict and promote its value.

这可能不是非常有效,但它应该有效.它也没有真正探索以列表作为值的字典,但您的示例数据没有它们,所以我没有实现.

This might not be super efficient, but it should work. It also does not really explore dictionaries with lists as values but your example data does not have them so I did not implement that.

import copy
import json

def find_replace(this_dict, target_key):
    ## optional depending on if you care that you mutate this_dict
    this_dict = copy.deepcopy(this_dict)

    for key in this_dict:
        # if the current value is a dict, dive into it
        if isinstance(this_dict[key], dict):
            this_dict[key] = find_replace(this_dict[key], target_key)

        # if the current key is our target merge the values and remove the key
        if key == target_key:
            this_dict = {**this_dict, **this_dict[key]}
            del this_dict[key]

    return this_dict

dict_nested = {
    "key_":{
        "key0a":{
            "key1a":{
                "sub_key2a":"sub_value2a", 
                "sub_key2b":"sub_value2b"
            }, 
            "key1b":"value1b"
        },
        "key0b":{
            "key_XYZ":{
                "key1a":{
                    "sub_key2a":"sub_value2a", 
                    "sub_key2b":"sub_value2b",
                    "key1a": {
                        "sub_key3a":"sub_value3a", 
                        "sub_key3b":"sub_value3b"
                    }, 
                }, 
                "key1b":"value1b"
            }
        }
    }
}

dict_nested_new = find_replace(dict_nested, "key1a")
print(json.dumps(dict_nested_new, indent=4))

应该给你:

{
    "key_": {
        "key0a": {
            "key1b": "value1b",
            "sub_key2a": "sub_value2a",
            "sub_key2b": "sub_value2b"
        },
        "key0b": {
            "key_XYZ": {
                "key1b": "value1b",
                "sub_key2a": "sub_value2a",
                "sub_key2b": "sub_value2b",
                "sub_key3a": "sub_value3a",
                "sub_key3b": "sub_value3b"
            }
        }
    }
}

请注意,我使用子嵌套键匹配添加了额外的嵌套级别,只是为了显示该场景.额外的优化,如支持列表和避免更新以合理费用提供的未更改密钥:-P

Note that I added an addition level of nesting with a sub-nested key match just to show that scenario. Additional optimizations like support for lists and avoiding updates to unchanged keys available for a reasonable fee :-P

这篇关于如何在深度嵌套的字典中出现所选键的任何位置用其值替换键:值对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆