Reputation: 65
I have an array with parameters - for each parameter I have a name and a value. Is there a way to format it dynamically into a string with a placeholders?
array:
[{'name': "a", 'value': "123"}, {'name': "b", 'value': "456"}]
string: "blabla {a}"
required result: "blabla 123"
Upvotes: 1
Views: 1136
Reputation: 1122232
Because your string input already uses valid string formatting placeholders, all you need to do is convert your existing data structure to a dictonary mapping names to values:
template_values = {d['name']: d['value'] for d in list_of_dictionaries}
then apply that dictionary to your template strings with the **mapping
call syntax to the str.format()
method on the template string:
result = template_string.format(**template_values)
Demo:
>>> list_of_dictionaries = [{'name': "a", 'value': "123"}, {'name': "b", 'value': "456"}]
>>> template_string = "blabla {a}"
>>> template_values = {d['name']: d['value'] for d in list_of_dictionaries}
>>> template_values
{'a': '123', 'b': '456'}
>>> template_string.format(**template_values)
'blabla 123'
Upvotes: 5