Tuesday, 15 June 2010

python - How to replace strings within dictionary values without using eval? -



python - How to replace strings within dictionary values without using eval? -

for example, i'd replace 'replacement' 'hello'

input:

d = { 'name': "string replacement", 'dictionaryb': { 'dictionary': 'replacement of string' }, 'dictionaryc': { 'anotherdictionary': { 'name': { 'replacementstring' } } } }

result:

{ 'dictionaryb': { 'dictionary': 'hello of string' }, 'dictionaryc': { 'anotherdictionary': { 'name': { 'hellostring' } } }, 'name': 'string hello' }

you need recursively, this

def rec_replacer(current_object): if isinstance(current_object, str): homecoming current_object.replace("replacement", "hello") elif isinstance(current_object, set): homecoming {rec_replacer(item) item in current_object} homecoming {key: rec_replacer(current_object[key]) key in current_object} print(rec_replacer(d))

output

{ 'dictionaryb': { 'dictionary': 'hello of string' }, 'dictionaryc': { 'anotherdictionary': { 'name': set(['hellostring']) } }, 'name': 'string hello' }

note: result has set(['hellostring']) because, {'replacementstring'} not dictionary, set object.

python string dictionary set

No comments:

Post a Comment