Python:用整数键解包字典?
有关词典,请参见以下内容:Python:用整数键解包字典?,python,dictionary,integer,string-formatting,unpack,Python,Dictionary,Integer,String Formatting,Unpack,有关词典,请参见以下内容: 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 1 is Stack and 2 is over and 3 is flow 但是,如果字典中的键是整数,我应该如何解压缩字典,例如: new_dict={1:'Stack', 2:'over', 3:'
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
1 is Stack and 2 is over and 3 is flow
但是,如果字典中的键是整数,我应该如何解压缩字典,例如:
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
在这种情况下,如何得到如下结果:
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
1 is Stack and 2 is over and 3 is flow
我知道有很多其他的方法可以做到这一点,但是在第一个例子中是否可以使用相同的策略呢。谢谢。您可以使用
dict.values()
,并且只能使用一个*
:
new_dict={1:'Stack', 2:'over', 3:'flow'}
print('1 is {} and 2 is {} and 3 is {}'.format(*new_dict.values()))
输出:
1 is Stack and 2 is over and 3 is flow
3 is flow and 1 is Stack and 2 is over
出现错误的原因是,您知道在f字符串中,大括号中的内容是在运行时计算的
因此,将数字作为键将使python认为键是正则整数
更新:
new_dict={1:'Stack', 2:'over', 3:'flow'}
print(f'3 is {new_dict[3]} and 1 is {new_dict[1]} and 2 is {new_dict[2]}')
输出:
1 is Stack and 2 is over and 3 is flow
3 is flow and 1 is Stack and 2 is over
它输出:
name is Stack and age is 11 and 1 is Stack and 2 is over and 3 is flow
你不能打开包装。你需要的是别的东西 函数调用中的
**
将dict解压为关键字参数,关键字参数名称始终为字符串。int1
不是有效的关键字参数名称。即使是,或者如果您将dict键转换为字符串,str.format
也不会寻找这样的关键字参数
{1}
,{2}
等。在格式中,查找位置参数,而不是关键字参数。无**
解包将产生位置参数。此外,由于它们是位置性的,如果从1开始,则需要在位置0处有一个伪参数,以便其他参数可以位于正确的位置
如果您真的希望使用dict和类似的格式字符串执行此操作,那么最简单的方法可能是遍历子类并重写:
非常感谢。但是,如果我希望结果为“1是堆栈,3是流”,意味着不列出所有元素或更改顺序,如“3是流,1是堆栈,2是结束”谢谢您的回答编号用于位置索引。也就是说,你可以(但可能不应该)做print('1是{0},2是{1},3是{2})。format(*new_dict))
或者最好是print(f'1是{new_dict[1]},2是{new u dict[2]},3是{new u dict[3]})
谢谢你的解释,下面是做这件事的代码。有什么问题吗?@ShivamJha:你在说你的答案吗?你的回答也不起作用。它也不能推广到其他格式字符串,而且如果k==list(my_dict.keys())[-1]
的效率非常低。