2

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.

1
  • 1
    Do you want replace anything between { and }. Or is there a set of very specific strings that you want to replace? Commented Oct 9, 2015 at 20:48

1 Answer 1

3

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'}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.