What is wrong in this piece of code?
dic = { 'fruit': 'apple', 'place':'table' }
test = "I have one {fruit} on the {place}.".format(dic)
print(test)
>>> KeyError: 'fruit'
Use format() function to format dictionary print in Python. Its in-built String function is used for the purpose of formatting strings according to the position. Python Dictionary can also be passed to format() function as a value to be formatted.
The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.
The format() function returns a formatted representation of a given value specified by the format specifier.
Should be
test = "I have one {fruit} on the {place}.".format(**dic)
Note the **
. format()
does not accept a single dictionary, but rather keyword arguments.
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