gpt4 book ai didi

python - 使用 str.format() 和字典

转载 作者:行者123 更新时间:2023-12-01 00:34:55 27 4
gpt4 key购买 nike

为什么这有效:

data = {'first': 'Hodor', 'last': 'Hodor!'}
print('{first} {last}'.format(**data))

这有效:

bdays = {
'Wesley Neill': 'January 6, 1985',
'Victoria Neill': 'August 25, 1992',
'Heather Neill': 'June 25, 1964'
}

print('\n {} \n {} \n {}'.format(*bdays))

但这不起作用:

 print('\n {} \n {} \n {}'.format(**bdays))

Traceback (most recent call last):
File "C:/Users/wesle/PycharmProjects/practicepython/birthdays.py", line 9, in <module>
print('We have the following names in our dictionary: \n {} \n {} \n {} \n'.format(**bdays))
IndexError: tuple index out of range

第一个示例在占位符大括号中包含字典键,并在参数中使用 **kwargs。

第二个没有键,并且 .format() 参数中只有一个星号。

第三个占位符中没有键,如示例 1 所示,但它在参数中使用 **kwargs。

我知道我需要做什么才能使事情正常进行,但我对这里的微妙之处感到好奇。

最佳答案

.format(**bdays) 等于 .format(key1=value, key2=value2,...),其中键是名称和值是生日。

因此,为了使其发挥作用,您的打印语句需要变为 -

print('\n {Wesley Neill} \n {Victoria Neill} \n {Heather Neill}'.format(**bdays))

这将打印这 3 个人的生日。

在 python 控制台中尝试以下操作 -

>>> [*bdays]
['Wesley Neill', 'Victoria Neill', 'Heather Neill']

关于python - 使用 str.format() 和字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57878333/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com