【发布时间】:2020-10-23 13:15:39
【问题描述】:
对于字典如下:
my_dict={'name':'Stack', 'age':11}
print('Name is {name} and age is {age}.'.format(**my_dict))
#output# Name is Stack and age is 11
但是,如果字典中的键是整数,我应该如何解包字典,例如:
new_dict={1:'Stack', 2:'over', 3:'flow'}
print('1 is {1} and 2 is {2} and 3 is {3}'.format(**new_dict))
#output error# tuple index out of range
在这种情况下,我怎样才能得到如下结果:
1 is Stack and 2 is over and 3 is flow
我知道可以通过许多其他方式做到这一点,但是否可以在第一个示例中使用相同的策略。谢谢。
【问题讨论】:
-
数字用于位置索引。 IE。你可以(但可能不应该)做
print('1 is {0} and 2 is {1} and 3 is {2}'.format(*new_dict))或者最好是print(f'1 is {new_dict[1]} and 2 is {new_dict[2]} and 3 is {new_dict[3]}') -
谢谢您的解释
标签: python dictionary integer string-formatting unpack