Python: dots in a variable name in a format string

Say I have a dictionary with dots in the field name, for example {'person.name': 'Joe'} . If I wanted to use this in str.format , is this possible?

My first instinct was

 'Name: {person.name}'.format(**{'person.name': 'Joe'}) 

but this will only work if my dict was configured as

 {'person':{'name':Joe}} 

The corresponding section of the docs manual does not mention exit from the point.

(Sidenote: I thought that usually

 def func(**kw): print(kw) func(**{'a.b': 'Joe'}) 

will lead to an error, but a call to ** -expanded functions works even if they are not valid identifiers! However, he makes a mistake on non-strings. o_o)

+7
source share
3 answers
 'Name: {0[person.name]}'.format({'person.name': 'Joe'}) 
+5
source

One way around this is to use the old % formatting (which is not outdated yet):

 >>> print 'Name: %(person.name)s' % {'person.name': 'Joe'} Name: Joe 
+3
source

I had a similar problem and decided to inherit it from string.Formatter :

 import string class MyFormatter(string.Formatter): def get_field(self, field_name, args, kwargs): return (self.get_value(field_name, args, kwargs), field_name) 

however you cannot use str.format() because it still points to the old formatter and you need to go this way

 >>> MyFormatter().vformat("{ab}", [], {'a.b': 'Success!'}) 'Success!' 
0
source

All Articles