[英]Recursively iterate through a nested dict with list, and replace matched values
I want to make a function that iterate through a nested dict that include list.我想创建一个遍历包含列表的嵌套字典的函数。 For each value that match with a keyword, the function replace it with another keyword.
对于与关键字匹配的每个值,该函数将其替换为另一个关键字。
It's not important if the function return another dict or if it change the main dict.函数是否返回另一个字典或是否更改主字典并不重要。
I tried to separate the case: - if the data is a dict, make something - if the data is a list, make something else我试图分开案例: - 如果数据是一个字典,做一些事情 - 如果数据是一个列表,做其他事情
DICT:字典:
data_dict = {
"name": "AAAAAA",
"content": "BBBBBB",
"dat": [
{
"author": {
"name": "CCCCCC",
"surname": "DDDDDD",
},
"title": "FFFFFF",
"color": 15258703,
"fields": [
{
"name": "GGGGGG",
"value": "HHHHHH",
},
{
"name": "IIIIII",
"value": "JJJJJJ",
}
],
"thumbnail": {
"url": "KKKKKK"
},
"image": {
"url": "LLLLLL"
},
"footer": {
"text": "MMMMMMM",
"icon_url": "NNNNNN"
}
}
]
}
Now I'm just trying to change each value to see if I'm iterate as well.现在我只是想改变每个值,看看我是否也在迭代。 I can print all the
data_dict
with value changed, but I can't manage it in a dict...我可以打印值已更改的所有
data_dict
,但我无法在 dict 中管理它...
def recursive_replace_valuer(data, match, repl):
if isinstance(data, list):
for l in data:
recursive_replace_valuer(l, match, repl)
if isinstance(l, dict):
recursive_replace_valuer(l, match, repl)
elif isinstance(data, dict):
for k,v in data.items():
recursive_replace_valuer(v, match, repl)
data[k] = '______'
print(data)
recursive_replace_valuer(data_dict, 'a','a')
The function should recursively apply the function to the values in a dict or a list until the input data
is neither a dict nor a list, at which point return the replacement value repl
if the given data match the given search string match
:该函数应该递归地将函数应用于字典或列表中的值,直到输入
data
既不是字典也不是列表,此时如果给定的数据匹配给定的搜索字符串match
则返回替换值repl
:
def replace(data, match, repl):
if isinstance(data, dict):
return {k: replace(v, match, repl) for k, v in data.items()}
elif isinstance(data, list):
return [replace(i, match, repl) for i in data]
else:
return repl if data == match else data
Or, to replace the original data in-place, make the function iterate through the given dict or list and replace a value by the key (for dict) or index (for list) if it's a match, and recursively apply the function to the value:或者,为了就地替换原始数据,使函数遍历给定的 dict 或列表,如果匹配,则用键(对于 dict)或索引(对于列表)替换值,然后将该函数递归地应用于价值:
def replace(data, match, repl):
if isinstance(data, (dict, list)):
for k, v in (data.items() if isinstance(data, dict) else enumerate(data)):
if v == match:
data[k] = repl
replace(v, match, repl)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.