When trying to run a script containing the following code for generating text block:
from textwrap import dedent
text = dedent("""\
yada yada '1' ('2','3',4')
('{0}', Null, '{1}',
'{
"Hello":"world",
}', '1', '{2}');""").format("yada1","yada2","yada3")
I get consistent error KeyError '\n "Hello"
and trace back pointing at the line of the .format()
.
When I remove the format
everything is ok, but I need it to enter parameters dynamically.
(Originally its reside inside a loop)
How to Fix the KeyError in Python Using the in Keyword. We can use the in keyword to check if an item exists in a dictionary. Using an if...else statement, we return the item if it exists or return a message to the user to notify them that the item could not be found.
A Python KeyError exception is what is raised when you try to access a key that isn't in a dictionary ( dict ). Python's official documentation says that the KeyError is raised when a mapping key is accessed and isn't found in the mapping. A mapping is a data structure that maps one set of values to another.
A KeyError is raised when you try to access a value from a dictionary that does not exist. To solve a key error, you can check for a key upfront before using it and only use it if the key exists. You can use a try… except block to handle a key error.
The Python "KeyError: 2" exception is caused when we try to access a 2 key in a a dictionary that doesn't contain the key. To solve the error, set the key in the dictionary before trying to access it or conditionally set it if it doesn't exist.
You need to double the {
and }
characters that are not placeholders:
text = dedent("""\
yada yada '1' ('2','3',4')
('{0}', Null, '{1}',
'{{
"Hello":"world",
}}', '1', '{2}');""").format("yada1","yada2","yada3")
otherwise Python sees a {\n "Hello":"world",\n}
placeholder, where the part up to the :
is the placeholder name.
From the Format String Syntax documenattion:
Format strings contain “replacement fields” surrounded by curly braces
{}
. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling:{{
and}}
.
(emphasis mine).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With