【发布时间】:2019-05-22 04:37:10
【问题描述】:
我从Python anti-patterns 得知你可以这样做:
person = {
'first': 'Tobin',
'age':20
}
print('{first} is {age} years old'.format(**person))
# Output: Tobin is 20 years old
person = {
'first':'Tobin',
'last': 'Brown',
'age':20
}
print('{first} {last} is {age} years old'.format(**person))
# Output: Tobin Brown is 20 years old
但是,当我的字典包含数字键时,它不起作用:
>>> d = {'123': 123}
>>> d
{'123': 123}
>>> print('{123} is 123 value'.format(**d))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
这适用于 Python 2 和 3。 这是已知的限制吗?
【问题讨论】:
-
我建议你检查一下这个answer
标签: python dictionary printing