字典(python)可以这样吗?不是弦而是跨度?

moiiocjp  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(228)

我对这本词典有个问题:
我们能创建一个像dict\ u 1这样的字典吗?

dict_1 = {Lily: [20], Tom: [21, 22]}
dict_2 = {'Lily': [20], 'Tom': [21, 22]}

我只见过像dict2这样的字典,但现在,我有了像dict1这样的字典。在我的字典里, Lily 实际上是一种.span(在空间中)。我不能用 print(dict_1['Lily']) 或者 print(dict_1[Lily]) 打印 20 ,它总是返回一个错误:

print(dict_1['Lily'])
KeyError:XXX 
(I understand this error)

or 
print(dict_1[Lily])
SyntaxError: invalid syntax
(I do not understand this error)

问题:
如何打印密钥的值 Lily 在字典1里(即 20 )
谢谢!

nx7onnlm

nx7onnlm1#

在python中,不能使用未定义的变量生成字典。

dict_1 = {Lily: [20], Tom: [21, 22]} # this will not work.

但如果将变量设置为字符串或其他变量,则其工作原理如下:

Lily = "Lily"
Tom = "Tom"

dict_1 = {Lily: [20], Tom: [21, 22]} # this works!

相关问题