ast.literal_eval 将 python 字典从外部文件导入主文件时出错

ast.literal_eval error when importing a python dictionary from external file to main file

到目前为止,我已经将词典转换为一系列列表,并查阅了文档和一些关于 SO 的问题。我有点困惑,因为字典是 ast.literal_eval() 可以处理的允许结构之一。

外部词典文件内容:

reports={
dict(DatabaseReports1='reports/dr_d1?'),
dict(DatabaseReports2='reports/dr_d2?'),
dict(DatabaseReports3='reports/dr_d3?'),
dict(TitleReports='reports/tr?'),
dict(BookReport1='reports/tr_b1?'),
dict(BookReport2='reports/tr_b2?'),
dict(BookReport3='reports/tr_b3?'),
dict(JournalReport1='reports/tr_j1?'),
dict(JournalReport2='reports/tr_j2?'),
}

主要文件内容:

with open('dictionaryFile.py', 'r') as f2:
        rs = f2.read()
        report=ast.literal_eval(rs)

我希望使用 ast 将文件从字符串转换为字典,但出现以下错误:

Traceback (most recent call last):
  File "mainFile.py", line 4, in <module>
   __import__("reportOptions")
  File "dictionaryFile.py", line 11, in <module>
    dict(JournalReport2='reports/tr_j2?'),
TypeError: unhashable type: 'dict'

您定义了 dictset,这就是您收到错误的原因。改为像这样定义 dict

此外,使用ast.literal_eval()时不能赋值,所以去掉report=

{
    'DatabaseReports': 'reports/dr_d1?',
    'DatabaseReports2': 'reports/dr_d2?',
    ...
}