1

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"

2
  • Is there a reason why your data is in that format? Instead of a list of dictionaries you should just store the name/value pairs in a dict. Commented Oct 8, 2018 at 8:08
  • Note: Python uses the name list, not array, for the mutable sequence data structure. There is a separate array module supporting a single numeric type for each value only. Commented Oct 8, 2018 at 8:10

1 Answer 1

5

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'
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.