Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use str.format() with a dictionary in python?

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'
like image 633
bogdan Avatar asked Jun 03 '11 16:06

bogdan


People also ask

How do I print a formatted dictionary in Python?

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.

What is the use of format () function in Python?

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.

What will the format () function return?

The format() function returns a formatted representation of a given value specified by the format specifier.


1 Answers

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.

like image 181
Sven Marnach Avatar answered Oct 05 '22 00:10

Sven Marnach