格式化字符串内的动态字典键

发布于 2025-01-16 11:50:43 字数 919 浏览 6 评论 0原文

考虑一下在字符串格式化中使用字典的简化示例:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

·深蓝 2025-01-23 11:50:43

您可以迭代年龄字典项目并将其传递给 .format()

template = 'My name is {name} and I am {age} years old.'

ages = {'name 1': 25, 'name 2': 22}

for name, age in ages.items():
    print(template.format(age=age, name=name))

输出:

My name is name 1 and I am 25 years old.
My name is name 2 and I am 22 years old.

You can iterate over the ages dict items and pass this to .format()

template = 'My name is {name} and I am {age} years old.'

ages = {'name 1': 25, 'name 2': 22}

for name, age in ages.items():
    print(template.format(age=age, name=name))

Output:

My name is name 1 and I am 25 years old.
My name is name 2 and I am 22 years old.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文