str.format() raises KeyError

45,660

The problem is those { and } characters you have there that don't specify a key for formatting. You need to double them up, so change your code to:

addr_list_formatted.append("""
    "{0}"
    {{
    "gamedir"  "str"
    "address"  "{1}"
    }}
""".format(addr_list_idx, addr))
Share:
45,660
Dor
Author by

Dor

Updated on July 02, 2020

Comments

  • Dor
    Dor almost 4 years

    The following code raises a KeyError exception:

    addr_list_formatted = []
    addr_list_idx = 0
    
    for addr in addr_list: # addr_list is a list
        addr_list_idx = addr_list_idx + 1
        addr_list_formatted.append("""
            "{0}"
            {
            "gamedir"  "str"
            "address"  "{1}"
            }
        """.format(addr_list_idx, addr))
    

    Why?

    I am using Python 3.1.

  • fijiaaron
    fijiaaron almost 8 years
    What if someone wanted to use JSON in Python?
  • mgc
    mgc almost 8 years
    @fijiaaron the double { in the answer is just to tell the format method that there is no key to format here (so they are escaped in the formated string and it shouldn't be a problem for build a JSON that way). Alternatively there is other efficient ways to manipulate strings, like the join method : "".join(['{"', var_name, '":', value, '}'])
  • Dmitry Kankalovich
    Dmitry Kankalovich almost 4 years
    I almost lost my mind until figured whats the problem
  • Lasse V. Karlsen
    Lasse V. Karlsen almost 4 years
    @DmitryKankalovich You have lost your mind, Stack Overflow, and everybody here, is just a figment of your imagination. (that's what I keep telling myself at least) :)