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.)
To insert a literal brace, double it up:
query = '{{"abc": "{abc}"}}'.format(abc=asset['abc'])
(This is documented here , but not highlighted particularly obviously).
wrap the outer braces in braces:
query = '{{"abc": "{abc}"}}'.format(abc=asset['abc'])
print query
{"abc": "def"}
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"}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.