'Search through dictionaries in another python file from string list
I have 2 files in a python directory. PyDir.File1.py contains dictionaries in this format:
PyDir.File1.py:
dict_1 = {records: "A", ...}
dict_2 = {records: "B", ...}
dict_3 = {records: "C", ...}
PyDir.File2.py imports PyDir.File1.py and has a list of strings with the string dictionaries I intend to call. I know I can call the dictionaries individually by importing them and calling them like this:
PyDir.File2.py:
import PyDir.File1
all_dicts = PyDir.File1
saved_dict = all_dicts.dict_1
print(saved_dict)
But is there anyway to access the dictionaries in File1 by passing it a list of strings as an argument? I have tried:
import PyDir.File1
dict_list = ["dict_1", "dict_2"]
all_dicts = PyDir.File1
for i in range(len(dict_list)):
saved_dict = all_dicts[dict_list[i]]
print(saved_dict)
And this gave me an error:
TypeError: 'module' object is not subscriptable
And I have tried to pass it as an extension of the address:
saved_dict = all_dicts.dict_list[i]
Any suggestions are appreciated.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
