因为您的字符串输入已经使用了有效的
string formatting placeholders
,您只需将现有数据结构转换为听写映射名称和值:
template_values = {d['name']: d['value'] for d in list_of_dictionaries}
然后将该字典应用于模板字符串,
**mapping
调用语法到
str.format()
method
在模板字符串上:
result = template_string.format(**template_values)
演示:
>>> 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'