str.format() raises KeyError

PythonSyntaxString FormattingDelimiterMissing Data

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDorView Question on Stackoverflow
Solution 1 - PythonLasse V. KarlsenView Answer on Stackoverflow