簡體   English   中英

如何在不使用eval的情況下替換字典值中的字符串?

[英]How to replace strings within dictionary values without using eval?

例如,我想將“替換”替換為“你好”

輸入:

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'
}

您需要像這樣遞歸地執行此操作

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對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM