gpt4 book ai didi

python - 如果在值中找到嵌套字典中另一个键的值,则替换字典中的值

转载 作者:行者123 更新时间:2023-11-30 22:18:14 25 4
gpt4 key购买 nike

我有以下嵌套字典:

 ex_dict = {'path1':
{'$variable1': '2018-01-01',
'$variable2': '2020-01-01',
'$variable3': '$variable1',
'$variable4': '$variable3'},
'path2':
{'$variable1': '2018-01-01',
'$variable2': '2020-01-01',
'$variable3': '$variable1',
'$variable4': '$variable1 + $variable2'}
}

如果在原始字典键的值中找到另一个字典值的键if,我想用另一个键的字典值替换为字典键指定的任何 $variableX 。请参阅下面的示例输出:

{'path1':
{'$variable1': '2018-01-01',
'$variable2': '2020-01-01',
'$variable3': '2018-01-01', # Substituted with value from key:variable1
'$variable4': '2018-01-01'}, # Substituted with value from key:variable3 (after variable3 was substituted with variable1)
'path2':
{'$variable1': '2018-01-01',
'$variable2': '2020-01-01',
'$variable3': '2018-01-01', # Substituted with value from key:variable1
'$variable4': '2018-01-01 + 2020-01-01'} # Substituted with value from key:variable3 (after variable3 was substituted with variable1) and key:variable2
}

有人有什么建议吗?

最佳答案

您可以通过递归遍历字典并使用 re 库进行替换来进行替换

import re

def process_dict(d):
reprocess = []
keys = d.keys()
while keys:
for k in keys:
v = d[k]
if isinstance(v, dict):
process_dict(v)
elif '$' in v:
d[k] = re.sub(r'\$\w+', lambda m: d[m.group(0)] if m.group(0) in d else m.group(0), v)
if '$' in d[k] and d[k] != v:
reprocess.append(k)
keys = reprocess
reprocess = []

编辑:

我添加了一个重新处理步骤来处理引用被链接并需要多次传递字典中的某些键才能完全处理它们的情况。

关于python - 如果在值中找到嵌套字典中另一个键的值,则替换字典中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49435546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com