用於從模板字符串渲染值的一種常用技術是這樣的:多級字典的Python字符串格式
>>> num = 7
>>> template = 'there were {num} dwarves'
>>> print template.format(**locals())
there were 7 dwarves
這種方法適用於具有__str__
方法的任何數據類型,例如類型的字典:
>>> data = dict(name='Bob', age=43)
>>> template = 'goofy example 1 {data}'
>>> print template.format(**locals())
goofy example 1 {'age': 43, 'name': 'Bob'}
然而,當一個字典項目是由鍵引用它不工作:
>>> template = 'goofy example 2 {data["name"]}'
>>> print template.format(**locals())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: '"name"'
它的不方便,而且似乎很奇怪,說這是有效的代碼格式字符串外面的標識是在格式字符串中使用時無效。我錯過了什麼嗎?有沒有辦法做到這一點?
我想能夠引用嵌套字典結構中的幾個圖層的元素,如somedict['level1key']['level2key']['level3key']
。到目前爲止,我唯一可行的方法是將這些值複製到只用於字符串格式的標量變量中,這是icky。
即使對於嵌套字典,它也可以工作。在正常代碼中可以像'x ['a'] ['b'] ['c']'引用的'x = dict(a = dict(b = dict(c = 123)))''像格式字符串中的''{x [a] [b] [c]}''一樣引用並正確渲染。謝謝! –