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))
Author by
Dor
Updated on July 02, 2020Comments
-
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 almost 8 yearsWhat if someone wanted to use JSON in Python?
-
mgc almost 8 years@fijiaaron the double
{
in the answer is just to tell theformat
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 thejoin
method :"".join(['{"', var_name, '":', value, '}'])
-
Dmitry Kankalovich almost 4 yearsI almost lost my mind until figured whats the problem
-
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) :)