Format: KeyError when using curly brackets in strings

后端 未结 3 2092
逝去的感伤
逝去的感伤 2021-01-04 08:37

I\'m running the following code:

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


        
3条回答
  •  长发绾君心
    2021-01-04 08:54

    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"}
    

提交回复
热议问题