bogdan
bogdan

Reputation: 9456

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

What is wrong with this piece of code?

dic = { 'fruit': 'apple', 'place':'table' }
test = "I have one {fruit} on the {place}.".format(dic)
print(test)

>>> KeyError: 'fruit'

Upvotes: 23

Views: 22788

Answers (3)

jfs
jfs

Reputation: 414159

There is ''.format_map() function since Python 3.2:

test = "I have one {fruit} on the {place}.".format_map(dic)

The advantage is that it accepts any mapping e.g., a class with __getitem__ method that generates values dynamically or collections.defaultdict that allows you to use non-existent keys.

It can be emulated on older versions:

from string import Formatter

test = Formatter().vformat("I have one {fruit} on the {place}.", (), dic)

Upvotes: 11

Sven Marnach
Sven Marnach

Reputation: 601529

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.

Upvotes: 43

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

You can use the following code too:

dic = { 'fruit': 'apple', 'place':'table' }
print "I have one %(fruit)s on the %(place)s." % dic

If you want to know more about format method use: http://docs.python.org/library/string.html#formatspec

Upvotes: 1

Related Questions