How to use dot in Python format strings?

I want to format the string and be able to use the dot operator so that I can build template strings containing, for example, {user.name} , {product.price} .

I tried this:

 'Hello {user.name}'.format( {'user': { 'name': 'Markus' } } ) KeyError: 'user' 'Hello {user.name}'.format( **{'user': { 'name': 'Markus' } } ) AttributeError: 'dict' object has no attribute 'name' 

Is there any way to do this?

+6
source share
2 answers

Python dict objects, unfortunately, are not an available attribute (i.e., with dot notation) by default. So you can either come to terms with uglier brackets:

 'Hello {user[name]}'.format( **{'user': { 'name': 'Markus' } } ) 

Or you can wrap your data in an object accessible by points. There are several classes of dictionaries available for accessing attributes that you can set from PyPI , for example stuf .

 from stuf import stuf 'Hello {user.name}'.format( **stuf({'user': { 'name': 'Markus' } }) ) 

I try to save my collections in stuf objects stuf that I can easily access them by attribute.

+7
source

The minimal change is to use square brackets in your template, not the period:

  # v Note >>> 'Hello {user[name]}'.format(**{'user': {'name': 'Markus'}}) 'Hello Markus' 

Alternatively, put objects that actually have this attribute in the dictionary, for example. custom class or collections.namedtuple :

 >>> class User(object): def __init__(self, name): self.name = name >>> 'Hello {user.name}'.format(**{'user': User('Markus')}) 'Hello Markus' 

Note also that if you are writing a literal, you can simply use the keyword argument:

 >>> 'Hello {user.name}'.format(user=User('Markus')) 'Hello Markus' 
+1
source

All Articles