Reputation: 63
I am trying to print variables and strings in a line. like [Hello! name How are you?] -> [Hello! John How are you?]
json file
#json01.json
{
"greet" : ["Hello! *name* How are you?"] # I don't know how to write this part..
}
and this is where I am..
import json
a = 'greet'
name = 'John'
with open('json01.json') as json_file:
json_dict = json.load(json_file)
if a in json_dict:
print(json_dict[a]) # I don't know how to write this part as well..
How should I do to get the result I want?
Sorry for the poor explanation and Thank you!
Upvotes: 4
Views: 249
Reputation: 91
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()
:
**
to extract keys from namespace
dictionary to "unpack" dictionary into .format()
arguments list to substitute keys by values in acquired stringAccording 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
.
Upvotes: 0
Reputation: 64338
There are various ways to format strings in python.
Here are 3 examples:
"Hello! %s How are you?" % name
"Hello! %(name)s How are you?" % locals()
"Hello! {name} How are you?".format(name=name)
Search the web for "python string formatting", and you'll find plenty of useful stuff.
Upvotes: 5