-2

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

我相信这段代码在语法上应该是正确的,但是,我似乎无法解压缩我的 dict 以传递给任何函数,不知道为什么这不起作用。

4

2 回答 2

1

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

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

但是,您的占位符仅适用于位置参数;没有任何名称或索引的占位符会自动编号:

"{} {} {} {} {}".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)(single *) 可以做到这一点,但是您还必须满足列出键的“任意”字典顺序。

于 2018-07-10T16:23:47.580 回答
-1

device_info = {'username': 'test', 'password': 'test', 'appliance': 'name', 'hostname': 'hostname', 'prodcut': 'juice'}

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

于 2018-07-10T16:58:58.303 回答