【问题标题】:python dictionary in a seperate filepython字典在一个单独的文件中
【发布时间】: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 json module, which is in the Python standard library 将 JSON 文件加载到字典中。

标签: python file dictionary


【解决方案1】:

file1.py

my_dict = {
    'key1': 'val1',
    'key2': 'val2',
    'keyn': 'valn',
}

file2.py

from file1 import my_dict

print(my_dict['key1'])

【讨论】:

  • 此评论与您的​​答案质量无关,更多的是理论性质。我想知道在这种情况下import 比 The Evil evalexec 好,考虑到导入文件时会发生这种情况?
【解决方案2】:

这里的问题是,您正试图将“字典”作为文件对象访问。每当您使用 read() 方法访问文件对象时。它给你一个字符串。

所以 dictionary = files.read() 是一个字符串。要将字符串转换为实际的字典对象,您可以使用 eval() 一个 python 内置函数。

dictionary = eval(files.read())

验证字典中是否存在“无论何时”键。使用,

if whenever in dictionary.keys():
    print(dictionary[whenever])

但是根据你的回溯结果,我在

看到了一个错误
elif whenever in get_close_matches(whenever, dict.keys()):

它说你的“dict”对象是字符串而不是字典。如果 dict 是用作字符串的字典。你可以使用,

elif whenever in get_close_matches(whenever, eval(dict).keys()):

如上所述。

【讨论】:

  • 这对于eval 来说是一个糟糕的用例。 (实际上,我认为 eval 的一个好的用例不存在。)ast.literal_eval 会更好,但更好的是要么导入模块(并让 Python 评估它),要么做一个小的修改并以 JSON 格式读取文件。
  • 另外,不要使用.keys() 来检查字典中的成员资格:更喜欢直接使用in 运算符,例如if mykey in mydict
  • @DanielPryden 我同意,如果在评估过程中更改字典的键和值,则 eval() 没有好的案例。正如帖子所有者所说,他是初学者。我想通过对他的代码进行最小的更改来帮助他。但感谢您纠正我。 :)
猜你喜欢
  • 2019-10-04
  • 1970-01-01
  • 1970-01-01
  • 2021-08-30
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 2013-08-09
  • 1970-01-01
相关资源
最近更新 更多