Dor Dor - 5 months ago 32
Python Question

str.format() raises KeyError

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.

Answer

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

addr_list_formatted.append("""
    "{0}"
    {{
    "gamedir"  "str"
    "address"  "{1}"
    }}
""".format(addr_list_idx, addr))
Comments