Home > Software engineering >  Search through dictionaries in another python file from string list
Search through dictionaries in another python file from string list

Time:03-09

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.

CodePudding user response:

Every module has a __dict__ attribute that puts all items in the module into a dictionary.

So you can do

PyDir.File1.__dict__["dict_1"]

to access the dict_1 dictionary.

If possible though, I would recommend not doing this and instead put all of those dicts into a dict in File1 itself:

dicts = {
    "dict_1" : {records: "A", ...},
    "dict_2" : {records: "B", ...},
    #...
}

this way you can just do

PyDir.File1.dicts["dict_1"]

and not rely on __dict__ which contains lots of other stuff and is considered a bit of a hack to use.

  • Related