Reputation: 1118
Let's say I have a nested dictionary like this:
example_dict = {
'key_one': '{replace_this}',
'key_two': '{also_replace_this} lorem ipsum dolor',
'key_three': {
'nested_key_one': '{and_this}',
'nested_key_two': '{replace_this}',
},
}
What is the best way to format the placeholder string values and either return a new a dictionary or edit the existing example_dict
? Also, account for any depth.
UPDATE
I tried out something else.
import json
output = json.dumps(example_dict)
output = output.format(replace_this='hello')
Although I get a KeyError on the first key it encounters from the .format() statement.
Upvotes: 2
Views: 3797
Reputation: 395
You could have another dict with your variables and a function that replaces them in string values recursively
def replace_in_dict(input, variables):
result = {}
for key, value in input.iteritems():
if isinstance(value, dict):
result[key] = replace_in_dict(value, variables)
else:
result[key] = value % variables
return result
example_dict = {
'key_one': '%(replace_this)s',
'key_two': '%(also_replace_this)s lorem ipsum dolor',
'key_three': {
'nested_key_one': '%(and_this)s',
'nested_key_two': '%(replace_this)s',
},
}
variables = {
"replace_this": "my first value",
"also_replace_this": "this is another value",
"and_this": "also this",
"this_is_not_replaced": "im not here"
}
print replace_in_dict(example_dict, variables)
# returns {'key_two': 'this is another value lorem ipsum dolor',
#'key_one': 'my first value',
# 'key_three': {'nested_key_two': 'my first value', 'nested_key_one': 'also this'}}
Upvotes: 3