Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: dots in the name of variable in a format string

Say I've got a dictionary with dots in the name of fields, like {'person.name': 'Joe'}. If I wanted to use this in str.format, is it possible?

My first instinct was

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

but this would only work if my dict were shaped like

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

The relevant manual docs section doesn't mention anyway of escaping the dot.

(Sidenote: I thought that generally

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

would cause an error, but the **-expanded function call seems to work even if they're not valid identifiers! It does error out on non-strings though. o_O)

like image 525
nfirvine Avatar asked Oct 28 '11 20:10

nfirvine


People also ask

Can variable name have dot?

A variable name in R programming language can contain numeric and alphabets along with special characters like dot (.) and underline (-).

What is Dot format in Python?

Python's str. format() technique of the string category permits you to try and do variable substitutions and data formatting. This enables you to concatenate parts of a string at desired intervals through point data format.


2 Answers

I had similar issue and I solved it by inheriting 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 can't use str.format() because it's still pointing to old formatter and you need to go like this

>>> MyFormatter().vformat("{a.b}", [], {'a.b': 'Success!'})
'Success!'
like image 152
Ski Avatar answered Sep 20 '22 10:09

Ski


'Name: {0[person.name]}'.format({'person.name': 'Joe'})
like image 24
Michael Hoffman Avatar answered Sep 17 '22 10:09

Michael Hoffman