For example, I have the following dict:
{'foo': 'test',
'bar': {'test1': 'some text here'},
'baz': {'test2': {'test3': 'some text here', 'test4': 'some text here'}}}
Or something like this, maybe more levels.
Now the question is, I want to change...'some text here'
to 'A test'
. Yeah, I can use a lot of for
loops like the following code:
d = {'foo': 'test',
'bar': {'test1': 'some text here'},
'baz': {'test2': {'test3': 'some text here',
'test4': 'some text here'}}}
for i in d:
if d[i] == 'some text here':
d[i] = 'A test'
elif type(d[i]) == dict:
for j in d[i]:
if d[i][j] == 'some text here':
d[i][j] = 'A test'
elif type(d[i][j]) == dict:
for n in d[i][j]:
if d[i][j][n] == 'some text here':
d[i][j][n] = 'A test'
__import__('pprint').pprint(d)
Output:
{'bar': {'test1': 'A test'},
'baz': {'test2': {'test3': 'A test', 'test4': 'A test'}},
'foo': 'test'}
However I don't think this is a good way...Any ideas?
As long as values you are changing are not too hairy, here's a one-liner:
In [29]: data = dict(foo=12, bar=dict(dd=12), ex=dict(a=dict(b=dict(v=12))))
In [30]: json.loads(re.sub("12", "33", json.dumps(data)))
Out[30]: {'bar': {'dd': 33}, 'ex': {'a': {'b': {'v': 33}}}, 'foo': 33}
EDIT, per Kevin, simple substitution doesn't even need re
:
json.loads(json.dumps(data).replace("12", "33"))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments