Python程序将字典视为字符串

Lan*_*rts -2 python dictionary

我设置了一个字典,并从文件中填充它,如下所示:

filedusers = {} # cheap way to keep track of users, not for production
FILE = open(r"G:\School\CS442\users.txt", "r")
filedusers = ast.literal_eval("\"{" + FILE.readline().strip() + "}\"")
FILE.close()
Run Code Online (Sandbox Code Playgroud)

然后我对它做了一个测试,像这样:

如果不是filedusers.get(words [0]):

where words[0]是用户名的字符串,但是我收到以下错误:

'str'对象没有属性'get'

但我已经证实,在FILE.close()我有一本字典后,它有正确的值.

知道发生了什么事吗?

Mar*_*eth 5

literal_eval接受一个字符串,并将其转换为python对象.所以,以下是真的......

ast.literal_eval('{"a" : 1}')
>> {'a' : 1}
Run Code Online (Sandbox Code Playgroud)

但是,您正在添加一些不需要的引用.如果您的文件只包含一个空字典({}),那么您创建的字符串将如下所示...

ast.literal_eval('"{}"') # The quotes that are here make it return the string "{}"
>> '{}'
Run Code Online (Sandbox Code Playgroud)

所以,解决方案是将线路改为......

ast.literal_eval("{" + FILE.readline().strip() + "}")
Run Code Online (Sandbox Code Playgroud)

...要么...

ast.literal_eval(FILE.readline().strip())
Run Code Online (Sandbox Code Playgroud)

..取决于您的文件布局.否则,由于引号,literal_eval会将您的字符串视为ACTUAL字符串.