python变量解压缩失败

时间:2018-07-10 16:19:02

标签: python python-2.7 dictionary string-formatting argument-unpacking

7.10,由于某种原因,以下代码段产生了错误...

device_info = {'username': 'test', 'password': 'test', 'appliance': 'name', 'hostname': 'hostname', 'prodcut': 'juice'}
print "{} {} {} {} {}".format(**device_info)

这引发了一个异常:

Traceback (most recent call last):
  File "python", line 4, in <module>
    print "{} {} {} {} {}".format(**device_info)
IndexError: tuple index out of range

我相信这段代码在语法上应该是合理的,但是,我似乎无法解译我的字典以传递给任何函数,不确定为什么它不起作用。

2 个答案:

答案 0 :(得分:1)

由于使用**语法,因此您将字段作为关键字参数传递:

"....".format(**device_info)
#             ^^

但是,您的占位符只适用于 positional 自变量;没有任何名称或索引的占位符会自动编号:

"{} {} {} {} {}".format(...)
# ^0 ^1 ^2 ^3 ^4

这就是为什么会出现索引错误,没有索引为0的位置参数。关键字参数没有索引的原因,因为它们本质上是字典中的键值对,是无序结构。

如果要将字典中的值包含在字符串中,则需要显式命名占位符:

"{username} {password} {appliance} {hostname} {prodcut}".format(**device_info)

(但请注意 product 的拼写错误为 prodcut ,您可能需要检查字典键的拼写是否正确)。

您将获得所有插入到指定插槽中的值:

>>> print "{username} {password} {appliance} {hostname} {prodcut}".format(**device_info)
test test name hostname juice

如果您希望打印,则必须将device_info键作为单独的位置参数进行传递; "...".format(*device_info)(单个*)可以做到这一点,但是您还必须满足于'arbitrary' dictionary order中列出密钥的要求。

答案 1 :(得分:-1)

device_info = {'用户名':'测试','密码':'测试','设备':'名称','主机名':'主机名','产品':'果汁'}

print(“ {用户名} {密码} {设备} {主机名} {产品}”。format(** device_info))