[英]Dynamically Iterating Through a Python Dictionary
我有一本看起来像这样的字典:
my_dict = {
'A': 'update_me',
'B': {
'C': 'D',
'E': 'F'
},
'G': {
'H': 'update_me',
'I': 'J',
'K': 'update_me'
}
}
我正在尝试创建一个 function ,它将遍历每个键值对并确定该值是否为update_me
。 如果是,它将将该值设置为等于this_worked
。 所以它看起来像这样:
my_dict = {
'A': 'this_worked',
'B': {
'C': 'D',
'E': 'F'
},
'G': {
'H': 'this_worked',
'I': 'J',
'K': 'this_worked'
}
}
除此之外,我希望它是动态的,这样代码就不必显式查找my_dict['A']
或my_dict['G']['H']
。 它应该只遍历每个键值对,如果该值是update_me
,则更新它(我还有其他字典需要以类似方式更新,但它们的键、长度和深度是不同的)。
我认为我真的只需要一种方法来遍历具有任意数量特定级别的字典的每个级别。
处理具有任意嵌套级别的操作的一种简单方法是递归 function。 在这种情况下,您希望对字典中的每个项目执行操作,并对本身是字典的每个项目执行相同的操作:
>>> 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'}}
一个解决方案可能是:
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
你可以通过这个来实现
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.