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'
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'
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.
** before the dictionary?** indicates that the dictionary should be expanded to a list of keyword parameters. The format method doesn't take a dictionary as a parameter, but it does take keyword parameters.dic = {'a':1,'b':2,'c':3} and call f(**dic)."I have one {0[fruit]} on the {0[place]}.".format(dic) works too - dic is the 0th positional argument here and you can access it's keys in the template.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)
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
% operator shouldn't be used in new code according to the Python documentation.% was meant to be deprecated in Python 3.1, but they never did. It won't go away soon (or probably not at all), so it's ok to still use it.format first because it's recommended, second because it seems cleaner.