【问题标题】:How to replace strings within dictionary values without using eval?如何在不使用 eval 的情况下替换字典值中的字符串?
【发布时间】:2014-10-23 12:52:24
【问题描述】:

例如,我想将 'Replacement' 替换为 'hello'

输入:

D = {
    'Name': "String Replacement",
    'DictionaryB': {
        'Dictionary': 'Replacement of the String'
    },
    'DictionaryC': {
        'AnotherDictionary': {
            'name': {
                'ReplacementString'
            }
        }
    }
}

结果:

{
    'DictionaryB': {
        'Dictionary': 'hello of the String'
    },
    'DictionaryC': {
        'AnotherDictionary': {
            'name': {
                'helloString'
            }
        }
    },
    'Name': 'String hello'
}

【问题讨论】:

    标签: python string dictionary set


    【解决方案1】:

    你需要递归地这样做,像这样

    def rec_replacer(current_object):
        if isinstance(current_object, str):
            return current_object.replace("Replacement", "hello")
        elif isinstance(current_object, set):
            return {rec_replacer(item) for item in current_object}
        return {key: rec_replacer(current_object[key]) for key in current_object}
    
    print(rec_replacer(D))
    

    输出

    {
        'DictionaryB': {
            'Dictionary': 'hello of the String'
        },
        'DictionaryC': {
            'AnotherDictionary': {
                'name': set(['helloString'])
            }
        },
        'Name': 'String hello'
    }
    

    注意:结果有set(['helloString']),因为{'ReplacementString'} 不是字典,而是set 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-27
      • 2019-10-09
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 1970-01-01
      • 1970-01-01
      • 2015-07-18
      相关资源
      最近更新 更多