从同样存储为变量的 Python 个模块中检索存储为变量的项目
Retrieving items that are stored as variables from Python modules that are also stored as variables
我正在使用 import_module 将多个 python 模块导入为循环中的变量。然后,在每个循环中,我需要检索不同的词典。我也将这些字典中的每一个都存储为变量。请参见下面的示例。我 运行 遇到了与 vals = test_file.item.get("text")
相关的问题,因为 test_file 没有名为 item.
的属性
最小可重现示例:
from importlib import import_module
file_list = ['file1','file2']
dict_list = ['test1','test2']
for file in file_list:
test_file = import_module(file)
for item in dict_list:
vals = test_file.item.get("text")
文件 1:
test1 = {
'text':['example1','example2','example3']
}
test2 = {
'text':['example1','example2','example3']
}
文件 2:
test1 = {
'text':['example1','example2','example3']
}
test2 = {
'text':['example1','example2','example3']
}
如何从同样存储为变量的文件中访问存储为变量的字典?
抱歉,如果这是转贴。我找不到这个。
您可以在模块上调用getattr
。
from importlib import import_module
file_list = ['file1','file2']
dict_list = ['test1','test2']
for file in file_list:
test_file = import_module(file)
for item in dict_list:
# getattr will return the attributes (test1, test2)
# from the module instance which you can then call .get() on
vals = getattr(test_file, item).get("text")
print(vals)
要首先检查属性的成员资格,您可以调用关联的 hasattr
。
我正在使用 import_module 将多个 python 模块导入为循环中的变量。然后,在每个循环中,我需要检索不同的词典。我也将这些字典中的每一个都存储为变量。请参见下面的示例。我 运行 遇到了与 vals = test_file.item.get("text")
相关的问题,因为 test_file 没有名为 item.
最小可重现示例:
from importlib import import_module
file_list = ['file1','file2']
dict_list = ['test1','test2']
for file in file_list:
test_file = import_module(file)
for item in dict_list:
vals = test_file.item.get("text")
文件 1:
test1 = {
'text':['example1','example2','example3']
}
test2 = {
'text':['example1','example2','example3']
}
文件 2:
test1 = {
'text':['example1','example2','example3']
}
test2 = {
'text':['example1','example2','example3']
}
如何从同样存储为变量的文件中访问存储为变量的字典?
抱歉,如果这是转贴。我找不到这个。
您可以在模块上调用getattr
。
from importlib import import_module
file_list = ['file1','file2']
dict_list = ['test1','test2']
for file in file_list:
test_file = import_module(file)
for item in dict_list:
# getattr will return the attributes (test1, test2)
# from the module instance which you can then call .get() on
vals = getattr(test_file, item).get("text")
print(vals)
要首先检查属性的成员资格,您可以调用关联的 hasattr
。