87

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.

dreftymac
  • 29,742
  • 25
  • 114
  • 177
Dor
  • 7,106
  • 4
  • 31
  • 45

1 Answers1

155

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))
MountainDrew
  • 383
  • 2
  • 18
Lasse V. Karlsen
  • 366,661
  • 96
  • 610
  • 798
  • 12
    What if someone wanted to use JSON in Python? – fijiaaron Jun 24 '16 at 00:47
  • 4
    @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, '}'])` – mgc Jun 24 '16 at 00:57
  • I almost lost my mind until figured whats the problem – Dmitry Kankalovich Jul 16 '20 at 01:53
  • 2
    @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) :) – Lasse V. Karlsen Jul 16 '20 at 11:11