1

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your nice suggestion!
1

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

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.