如果在值中找到嵌套字典中另一个键的值,请替换字典中的值 [英] Replace values in dict if value of another key within a nested dict is found in value

查看:31
本文介绍了如果在值中找到嵌套字典中另一个键的值,请替换字典中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下嵌套的字典:

 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.请参见下面的示例输出:

I want to replace any $variableX specified for a dict key with the dict value from another key if the key from the other dict value if found in the value of the original dict key. See example output below:

{'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 库进行替换来进行替换

You could do replacement by recursively walking through the dict and using the re library to do the replacements

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 = []

我添加了一个重新处理步骤,以处理引用被链接并且需要多次通过字典中的某些键才能完全处理它们的情况.

I added a reprocessing step to handle the cases where the references are chained and require multiple passes through some keys in the dictionary to fully process them.

这篇关于如果在值中找到嵌套字典中另一个键的值,请替换字典中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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