0

I have a dictionary that prints well

print(
    """{ASSET_EDGE_CONFIG[EndAdvertiserAdAccounts][hive_data_features][rev_28d]}""".format(**locals())
)

But I want to parametrize 'EndAdvertiserAdAccounts' key to something like below

EDGE = 'EndAdvertiserAdAccounts'
print(
    """{ASSET_EDGE_CONFIG[{EDGE}][hive_data_features][rev_28d]}""".format(**locals())
)

above code gives me following error:

KeyError: '{EDGE}'

I guessing there is a particular way to formatting dict using format function. Any help is appreciated here

1
  • 4
    Why are you using such complex string formatting and locals? Is there something in your use case which could not be achieved instead by computing the value first and then printing it? That would be a more typical approach. Commented Jul 2, 2015 at 16:42

1 Answer 1

2

What you're asking for is not possible with the string format function. As Ming points out you're using string format in a very odd way. The specification for string format is here. What you're asking about is basically the element_index specification which says the stuff inside the square braces has to either be an integer or string constant. Your example would try to do `ASSERT_EDGE_CONFIG["{EDGE}"]...

If this is all you're trying to do then the following would make better sense:

print ASSET_EDGE_CONFIG[EDGE]["hive_data_features"]["rev_28d"]

Assuming the more likely case that you're trying to do something more interesting it would be worth giving a more complicated example to show us why you want to use string format.

If you really wanted I guess you could do (requires two format calls):

EDGE = 'EndAdvertiserAdAccounts'
print(
    """{{ASSET_EDGE_CONFIG[{EDGE}][hive_data_features][rev_28d]}}""".format(**locals()).format(**locals())
)
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.