How do I format a string using a dictionary in python-3.x?

How do I format a string using a dictionary in python-3.x?

Is this good for you?

geopoint = {latitude:41.123,longitude:71.091}
print({latitude} {longitude}.format(**geopoint))

To unpack a dictionary into keyword arguments, use **. Also,, new-style formatting supports referring to attributes of objects and items of mappings:

{0[latitude]} {0[longitude]}.format(geopoint)
The title is {0.title}s.format(a) # the a from your first example

How do I format a string using a dictionary in python-3.x?

As Python 3.0 and 3.1 are EOLed and no one uses them, you can and should use str.format_map(mapping) (Python 3.2+):

Similar to str.format(**mapping), except that mapping is used directly and not copied to a dict. This is useful if for example mapping is a dict subclass.

What this means is that you can use for example a defaultdict that would set (and return) a default value for keys that are missing:

>>> from collections import defaultdict
>>> vals = defaultdict(lambda: <unset>, {bar: baz})
>>> foo is {foo} and bar is {bar}.format_map(vals)
foo is <unset> and bar is baz

Even if the mapping provided is a dict, not a subclass, this would probably still be slightly faster.

The difference is not big though, given

>>> d = dict(foo=x, bar=y, baz=z)


>>> foo is {foo}, bar is {bar} and baz is {baz}.format_map(d)

is about 10 ns (2 %) faster than

>>> foo is {foo}, bar is {bar} and baz is {baz}.format(**d)

on my Python 3.4.3. The difference would probably be larger as more keys are in the dictionary, and

Note that the format language is much more flexible than that though; they can contain indexed expressions, attribute accesses and so on, so you can format a whole object, or 2 of them:

>>> p1 = {latitude:41.123,longitude:71.091}
>>> p2 = {latitude:56.456,longitude:23.456}
>>> {0[latitude]} {0[longitude]} - {1[latitude]} {1[longitude]}.format(p1, p2)
41.123 71.091 - 56.456 23.456

Starting from 3.6 you can use the interpolated strings too:

>>> flat:{p1[latitude]} lng:{p1[longitude]}
lat:41.123 lng:71.091

You just need to remember to use the other quote characters within the nested quotes. Another upside of this approach is that it is much faster than calling a formatting method.

Leave a Reply

Your email address will not be published. Required fields are marked *