例如,我想将'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'
}
答案 0 :(得分: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
对象。