Python3: Str.format Keyerror Solution for incoming parameter error

Python3 str.format Keyerror solution for incoming parameter error

Additional knowledge of keyerror description and solution

Keyerror description and solution

If the parameter is called in the way of ‘W’, keyerror will be generated

# Define the variable c
>>>c = {'w':'w', 'o': 'o', 'r': 'r', 'l': 'l', 'd': 'd'}
{'w':'w', 'o': 'o', 'r': 'r', 'l': 'l', 'd': 'd'}
# Calling the parameter with 'w' will generate a KeyError error
>>>"Hello, {'w'}{'o'}{'r'}{'l'}{'d'}!".format(**c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'w'

Solution:

# Remove the single quotes and it'll be fine
>>> "Hello, {o}{r}{l}{d}!".format(**c)
Hello, world!

But I don’t understand the principle, I need to continue to learn.

Supplementary knowledge

When dict() is called to generate a dictionary, the key reference does not need to add single quotation marks.

>>>dict(w='w', o='o', r='r')
{'w': 'w', 'o': 'o', 'r': 'r'}


Read More: