开发者

Python program treating dictionary like a string

I set up a dictionary, and filled it from a file, like so:

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()

then later I did a test on it, like this:

if not filedusers.get(words[0]):

where words[0] is a string for a username, but I get the following error:

'str' object has no attribute 'get'

but I verif开发者_JS百科ied already that after the FILE.close() I had a dictionary, and it had the correct values in it.

Any idea what's going on?


literal_eval takes a string, and converts it into a python object. So, the following is true...

ast.literal_eval('{"a" : 1}')
>> {'a' : 1}

However, you are adding in some quotations that aren't needed. If your file simply contained an empty dictionary ({}), then the string you create would look like this...

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

So, the solution would be to change the line to...

ast.literal_eval("{" + FILE.readline().strip() + "}")

...or...

ast.literal_eval(FILE.readline().strip())

..depending on your file layout. Otherwise, literal_eval sees your string as an ACTUAL string because of the quotes.


>>> import ast
>>> username = "asd: '123'"
>>> filedusers = ast.literal_eval("\"{" + username + "}\"")
>>> print filedusers, type(filedusers)
{asd} <type 'str'>

You don't have a dictionary, it just looks like one. You have a string.


Python is dynamically typed: it does not require you to define variables as a specific type. And it lets you define variables implicitly. What you are doing is defining filedusers as a dictionary, and then redefining it as a string by assigning the result of ast.literal_eval to it.

EDIT: You need to remove those quotes. ast.literal_eval('"{}"') evaluates to a string. ast.literal_eval('{}') evaluates to a dictionary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜