In case you want to "substitute" more than only one variable into string, with pointing out explicitly what do you want to instantiate without typing many arguments in .format():
- Create a dictionary. Keys should be strings to be replaced in acquired string and values should be variables that will appear in place of keys.
- Use double asterisk
** to extract keys from namespace dictionary to "unpack" dictionary into .format() arguments list to substitute keys by values in acquired string
According to your example:
import json
a = 'greet'
name = 'John'
weight = 80
height = 190
age = 23
# 1.
namespace = {'name': name, 'age': age, 'weight': weight, 'height': height}
json_dict_all_keys = json.loads('{"greet" : "Hello! {name}, {age} years old, {height}cm, {weight}kg. How are you?"}')
json_dict_some_keys = json.loads('{"greet" : "Hello! {name}, {weight}kg. How are you?"}')
json_dict_mixed_keys = json.loads('{"greet" : "Hello! {name}, {other} years old, {key}cm, {weight}kg. How are you?"}')
json_dict_none_of_keys = json.loads('{"greet" : "Hello! {some}, {other} years old, {key}cm, {here}kg. How are you?"}')
if a in json_dict:
# 2.
print(json_dict_all_keys[a].format(**namespace)) # Hello! John, 23 years old, 190cm, 80kg. How are you?
print(json_dict_some_keys[a].format(**namespace)) # Hello! John, 80kg. How are you?
print(json_dict_mixed_keys[a].format(**namespace)) # Raising KeyError!
print(json_dict_none_of_keys[a].format(**namespace)) # Raising KeyError too!
As you can see, there is no requirement to use all of "keys" from namespace.
But be careful - when in string you want to format appears "key" that is not included in namespace KeyError will occur.
To simplify explaination I used json.loads instead of loading json from file with json.load.
nameinserted in the right place. The existing code ignores that completely.