Reputation: 83
I want to be able to access a key in a dictionary that has a dot with str.format()
. How can I do that?
For example format for a key without a dot works:
>>> "{hello}".format(**{ 'hello' : '2' })
'2'
But it doesn't when the key has a dot in it:
>>> "{hello.world}".format(**{ 'hello.world' : '2' })
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'hello'
Upvotes: 8
Views: 3409
Reputation: 1121256
You cannot. The Format String Syntax supports only integers or valid Python identifiers as keys. From the documentation:
arg_name ::= [identifier | integer]
where identifier
is defined as:
Identifiers (also referred to as names) are described by the following lexical definitions:
identifier ::= (letter|"_") (letter | digit | "_")*
No dots (or semicolons) allowed.
You could use your dictionary as a second level object:
"{v[hello.world]}".format(v={ 'hello.world' : '2' })
Here we assigned the dictionary to the name v
, then index into it using a key name. These can be any string, not just identifiers.
Upvotes: 8