Reputation: 1311
I am trying to pass a dictionary (loaded from JSON file) to format string. While single key-value unpack works correctly, I am not sure how I can access the nested keys (children) with a format string.
Or is there any other better way to pass JSON to string format?
config = {
"TEST": "TEST",
"TEST1": "TEST1",
"TEST2": {
"TEST21": "TEST21"
}
}
query_1 = """
{TEST} {TEST1}
"""
query_2 = """
{TEST} {TEST1}
{TEST2.TEST21}
"""
print(query_1.format( **config )) # WORKING
print(query_2.format( **config )) # NOT WORKING
Upvotes: 1
Views: 180
Reputation: 14218
Using f-string
config = {
"TEST": "TEST",
"TEST1": "TEST1",
"TEST2": {
"TEST21": "TEST21"
}
}
query_2 = f"""
{config['TEST']} {config['TEST1']}
{config['TEST2']['TEST21']}
"""
print(query_2)
Note, if query is sql query, there is probably better way to do what you do, not using string formatting
Upvotes: 1
Reputation: 7896
In your query_2
change {TEST2.TEST21}
to {TEST2[TEST21]}
it will work.
Ex.
query_2 = """
{TEST} {TEST1}
{TEST2[TEST21]}
"""
print(query_2.format(**config))
Output
TEST TEST1
TEST21
Upvotes: 1