【发布时间】:2019-01-28 04:23:58
【问题描述】:
我有一本很长的字典,我不想把它和我的程序放在同一个文件中。我尝试访问字典,但出现错误:
Traceback (most recent call last):
File "C:\Users\....\OneDrive\Documents\python\atom\datesandtimes.py", line 22, in <module>
elif whenever in get_close_matches(whenever, dict.keys()):
AttributeError: 'str' object has no attribute 'keys'
是否可以将它用作字典或转换它,还是我必须将整个字典放在主文件中?我的程序是:
with open("dates.py") as files:
dictionary = files.read()
if whenever in files:
print(dictionary[whenever])
elif whenever in get_close_matches(whenever, dict.keys()):
date = whenever in get_close_matches(whenever, dict.keys())
print(dates[date])
我是初学者,所以如果我问一个没有意义的问题,请告诉我。
【问题讨论】:
-
您以
dictionary开头,然后使用dict.keys()。试试dictionary.keys()。您的错误是说dict只是一个字符串,仅此而已 -
这里发生了很多事情,而且可能不止一个问题。我不能肯定地说,因为你还没有发布完整的程序。请发送MCVE 来解决问题。
-
另外,dict 是一个字符串的事实是一个问题:dict 应该是一个类...
-
如果目标只是将数据存储在单独的文件中,我建议使用JSON,这与您编写 Python dict 的方式非常相似。您可以使用 the
jsonmodule, which is in the Python standard library 将 JSON 文件加载到字典中。
标签: python file dictionary