You are given:
-
A dictionary (map) of placeholder keys to values, for example:
values = {
"db_host": "example.com",
"db_port": 5001
}
-
A template string that may contain placeholders wrapped in double curly braces
{{
and
}}
, for example:
"application is now connecting to {{db_host}}:{{db_port}}"
Task 1
Implement a function that replaces each placeholder in the template string with the corresponding value from the dictionary. For the example above, the output should be:
"application is now connecting to example.com:5001"
Assume:
-
All placeholders appearing in the template exist as keys in the dictionary.
-
Placeholders consist of letters, digits, and underscores only.
Describe your approach and then implement the function in a programming language of your choice.
Task 2 (Follow-up)
Now, instead of a single template string, you are given another dictionary where each value is a template string that may contain the same kind of {{key}} placeholders, and you are also given the same values dictionary used for substitution.
Example:
values = {
"db_host": "example.com",
"db_port": 5001
}
templates = {
"conn_msg": "application is now connecting to {{db_host}}:{{db_port}}",
"short_msg": "{{db_host}}:{{db_port}}"
}
Implement a function that takes values and templates and returns a new dictionary where each value in templates has had its placeholders replaced using values.
Explain your algorithm, including its time complexity in terms of:
-
L
= total length of all template strings
-
K
= number of distinct keys in the
values
dictionary.