19

I'm running the following code:

asset = {}
asset['abc'] = 'def'
print type(asset)
print asset['abc']
query = '{"abc": "{abc}"}'.format(abc=asset['abc'])
print query

Which throws a KeyError error:

[user@localhost] : ~/Documents/vision/inputs/perma_sniff $ python ~/test.py 
<type 'dict'>
def
Traceback (most recent call last):
  File "/home/user/test.py", line 5, in <module>
    query = '\{"abc": "{abc}"\}'.format(abc=asset['abc'])
KeyError: '"abc"'

Format is obviously getting confused by the wrapping {. How can I make sure format only tries to replace the (correct) inner {abc}.

ie, expected output is:

{"abc": "def"}

(I'm aware I could use the json module for this task, but I want to avoid that. I would much rather use format.)

3 Answers 3

41

To insert a literal brace, double it up:

query = '{{"abc": "{abc}"}}'.format(abc=asset['abc'])

(This is documented here, but not highlighted particularly obviously).

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

Comments

5

wrap the outer braces in braces:

query = '{{"abc": "{abc}"}}'.format(abc=asset['abc'])
print query
{"abc": "def"}

2 Comments

think your double close brace is on the wrong one. should be: '{{"abc": "{abc}"}}'
@tom, yep, typo fixed
2

The topmost curly braces are interpreted as a placeholder key inside your string, thus you get the KeyError. You need to escape them like this:

asset = {}
asset['abc'] = 'def'
query = '{{"abc": "{abc}"}}'.format(**asset)

And then:

>>> print query
{"abc": "def"}

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.