1

A common technique for rendering values from template strings looks like this:

>>> num = 7
>>> template = 'there were {num} dwarves'
>>> print template.format(**locals())
there were 7 dwarves

This approach works for any data type that has a __str__ method, e.g. dicts:

>>> data = dict(name='Bob', age=43)
>>> template = 'goofy example 1 {data}'
>>> print template.format(**locals())
goofy example 1 {'age': 43, 'name': 'Bob'}

However it doesn't work when a dict item is referenced by key:

>>> template = 'goofy example 2 {data["name"]}'
>>> print template.format(**locals())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: '"name"'

It's inconvenient, and seems odd, that an identifier that's valid in code outside the format string is invalid when used within the format string. Am I missing something? Is there a way to do this?

I'd like to be able to reference an element several layers down in a nested dictionary structure, like somedict['level1key']['level2key']['level3key']. So far my only workable approach has been to copy these values to a scalar variable just for string formatting, which is icky.

1 Answer 1

3

You can do it by using {data[name]} instead of {data["name"]} in the string.

The types of things you can specify in a format string are restricted. Arbitrary expressions aren't allowed, and keys are interpreted in a simplified way, as described in the documentation:

it is not possible to specify arbitrary dictionary keys (e.g., the strings '10' or ':-]') within a format string.

In this case, you can get your key out because it's a simple alphanumeric string, but, as the docs suggest, you can't always necessarily do it. If you have weird dict keys, you may have to change them to use them in a format string, or resort to other methods (like concatening string values explicitly with +).

Sign up to request clarification or add additional context in comments.

1 Comment

That works, even for a nested dictionary. A structure like x = dict(a=dict(b=dict(c=123))) that could be referenced like x['a']['b']['c'] in normal code can be referenced like '{x[a][b][c]}' in a format string and rendered properly. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.