Format: KeyError when using curly brackets in strings

后端 未结 3 2082
逝去的感伤
逝去的感伤 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:48

    To insert a literal brace, double it up:

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

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

    0 讨论(0)
  • 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"}
    
    0 讨论(0)
  • 2021-01-04 09:09

    wrap the outer braces in braces:

    query = '{{"abc": "{abc}"}}'.format(abc=asset['abc'])
    print query
    {"abc": "def"}
    
    0 讨论(0)
提交回复
热议问题