4

Format: KeyError when using string hooks

 2 years ago
source link: https://www.codesd.com/item/format-keyerror-when-using-string-hooks.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Format: KeyError when using string hooks

advertisements

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).


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK