Reputation: 7986
I'm getting the following error, how should I fix it?
KeyError: 'a' Process finished with exit code 1
s = """
a b c {a}
""".format({'a':'123'})
print s
Upvotes: 4
Views: 2353
Reputation: 362488
Named formatting variables must be passed by name:
>>> s = """
... a b c {a}
... """.format(a=123)
>>> print(s)
a b c 123
If you're providing a dict of data, you can "unpack" the names:
>>> d = {'a': 123}
>>> s = """
... a b c {a}
... """.format(**d)
>>> print(s)
a b c 123
Upvotes: 3
Reputation: 490
You are using the format
method for strings incorrectly. format
requires that you pass in keyword arguments when you want to substitute names inside a string.
The correct form to use the method in your case would be the following:
s = """
a b c {a}
""".format(a='123')
print s
However if you do want to pass in a dictionary, then you can unpack it into keyword arguments by prepending **
before the dictionary itself. This will unpack the dictionary into the the keyword argument of a='123'
like the code above.
Please read more about Python strings and the string format method here.
Upvotes: 1
Reputation: 152587
You need to pass in the arguments by name .format(a=123)
or use format_map
which expects a dictionary:
s = """
a b c {a}
""".format_map({'a':'123'})
Upvotes: 6