简体   繁体   English

通过 Python 字典动态迭代

[英]Dynamically Iterating Through a Python Dictionary

I have a dictionary that looks like:我有一本看起来像这样的字典:

my_dict = {
   'A': 'update_me',
   'B': {
       'C': 'D',
       'E': 'F'
   },
   'G': {
       'H': 'update_me',
       'I': 'J',
       'K': 'update_me'
   }
}

I'm trying to create a function that will loop through every key value pair and determine if that value is update_me .我正在尝试创建一个 function ,它将遍历每个键值对并确定该值是否为update_me If it is, it will set that value equal to this_worked .如果是,它将将该值设置为等于this_worked So it'd look like this:所以它看起来像这样:

my_dict = {
   'A': 'this_worked',
   'B': {
       'C': 'D',
       'E': 'F'
   },
   'G': {
       'H': 'this_worked',
       'I': 'J',
       'K': 'this_worked'
   }
}

In addition to this , I would like this to be dynamic, so that the code doesn't have to explicitly look for my_dict['A'] or my_dict['G']['H'] .除此之外,我希望它是动态的,这样代码就不必显式查找my_dict['A']my_dict['G']['H'] It should just loop through each key value pair, and if that value is update_me , then update it (I have other dictionaries that I need to update in a similar way, but their keys, lengths and depths are varying).它应该只遍历每个键值对,如果该值是update_me ,则更新它(我还有其他字典需要以类似方式更新,但它们的键、长度和深度是不同的)。

I think I really just need a way to loop through every level of a dictionary that has any number of particular levels.我认为我真的只需要一种方法来遍历具有任意数量特定级别的字典的每个级别。

An easy way to handle operations with arbitrary levels of nesting is a recursive function.处理具有任意嵌套级别的操作的一种简单方法是递归 function。 In this case, you want to perform an operation on each item in a dictionary, and do that same thing for each item that is itself a dictionary:在这种情况下,您希望对字典中的每个项目执行操作,并对本身是字典的每个项目执行相同的操作:

>>> def recursive_replace(d, old, new):
...     if d == old:
...         return new
...     if not isinstance(d, dict):
...         return d
...     return {k: recursive_replace(v, old, new) for k, v in d.items()}
...
>>> recursive_replace(my_dict, "update_me", "this_worked")
{'A': 'this_worked', 'B': {'C': 'D', 'E': 'F'}, 'G': {'H': 'this_worked', 'I': 'J', 'K': 'this_worked'}}

A solution could be:一个解决方案可能是:

def replace(my_dict, old_test="update_me", new_text="this_worked"):
    for x, y in my_dict.items():
        if type(y) is dict:
            replace(y)
        elif type(y) is str:
            if y == old_text:
                y = new_text
            my_dict[x] = y
    return my_dict

You can achieve this by this你可以通过这个来实现

my_dict = {
   'A': 'update_me',
   'B': {
       'C': 'D',
       'E': 'F'
   },
   'G': {
       'H': 'update_me',
       'I': 'J',
       'K': 'update_me'
   }
}

old_value = "update_me"
new_value = "new_value"

def replace_value(my_dict, old_value, new_value):
    for key, value in my_dict.items():
        if type(value) is dict:
            replace_value(value, old_value, new_value)
        elif value == old_value:
            my_dict[key] = new_value
    return my_dict
        

my_dict = replace_value(my_dict, old_value, new_value)
print(my_dict)

# {'A': 'new_value', 'B': {'C': 'D', 'E': 'F'}, 'G': {'H': 'new_value', 'I': 'J', 'K': 'new_value'}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM