格式化字符串内的动态字典键
考虑一下在字符串格式化中使用字典的简化示例:
template = 'My name is {name}, I am {ages[name]} years old and I am a {occupations[name]}.'
ages = {'name 1': 25, 'name 2:': 22}
occupations {'name 1': 'programmer', 'name 2': 'mechanic'}
for name in ages.keys():
print(template.format(ages=ages, occupations=occupations, name=name))
这会导致 KeyError: 'name'
好吧,很公平,也许我需要
template = 'My name is {name}, I am {ages[{name}]} years old and I am a {occupations[{name}]}'
但是不,KeyError: '{name}'
code>
我知道在这种情况下我可以做
template = 'My name is {name}, I am {age} years old and I am a {occupation}.'
(...)
print(template.format(age=ages[name], occupation=occupations[name], name=name))
或者您可以压缩字典并循环遍历键和项目,但是有没有一种方法可以更类似于我的第一个示例,即提供完整的字典.format()
适用于任意数量的字典?
换句话说:有没有办法在Python中的格式化字符串中使用动态键?
Consider this simplified example of using a dictionary in string formatting:
template = 'My name is {name}, I am {ages[name]} years old and I am a {occupations[name]}.'
ages = {'name 1': 25, 'name 2:': 22}
occupations {'name 1': 'programmer', 'name 2': 'mechanic'}
for name in ages.keys():
print(template.format(ages=ages, occupations=occupations, name=name))
which results in KeyError: 'name'
OK, fair enough, maybe I need
template = 'My name is {name}, I am {ages[{name}]} years old and I am a {occupations[{name}]}'
But no, KeyError: '{name}'
I know that in this instance I can do
template = 'My name is {name}, I am {age} years old and I am a {occupation}.'
(...)
print(template.format(age=ages[name], occupation=occupations[name], name=name))
Or you can zip the dicts and loop over both the keys and the items, but is there a way to do it more akin to my first example, i.e. supplying the complete dictionaries to .format()
that works for any number of dicts?
In other words: Is there any way to use dynamic keys in a formatted string in Python?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以迭代年龄字典项目并将其传递给 .format()
输出:
You can iterate over the ages dict items and pass this to .format()
Output: