GainesvilleJesus
GainesvilleJesus

Reputation: 27

Python Dictionary Object Instantiation NameError

I am making a console application that can load different dictionaries filled with Spanish words and definitions, my thinking here is that I want to make all the objects of my Dictionary class in this module and then import them via one dict_of_dicts into main.py. Instead of writing out each instantiating each individual object like so:

animals_dict = Dictionary('animals') 

I wanted to loop through my dict_of_dicts and create them. Now when I do this I get a NameError because these objects are not yet defined, which makes sense I suppose, but I was wondering if there is a work around here to make these objects by a loop instead of just writing them out one by one.

# list of dictionaries loaded into main.py at runtime

from dict_class import Dictionary

dict_of_dicts = {'animals':animals_dict, 'nature':nature_dict, 'irregulars':irregulars_dict,
         'clothes':clothes_dict, 'foodbev':foodbev_dict, 'phrases':phrases_dict,
            'verbs':verbs_dict,'adjectives':adjectives_dict,'future':future_dict,'past':past_dict,
             'wotd':wotd_dict}

for k,v in dict_of_dicts:
    v = Dictionary(k)  #k=self.name
    print(v) #v=object

Upvotes: 0

Views: 295

Answers (2)

sytech
sytech

Reputation: 40941

Suppose you have a list of names ['animals', 'nature', 'irregulars'] #etc

You can loop over that to create a new dictionary

my_dicts = {}
names = ['animals', 'nature', 'irregulars']
for name in names:
    my_dicts[name] = Dictionary(name)

Or as a comprehension

my_dicts = {name: Dictionary(name) for name in names}

Besides the object not existing yet, the other problem you would run into is that when looping over a dictionary's items through dict.items, making an assignment on that name will not actually modify the dictionary.

for key, value in some_dict.items():
    value = 'new' # Bad. Does not modify some_dict

for key in some_dict:
    some_dict[key] = 'new' # Good. Does modify some_dict

Upvotes: 1

ingvar
ingvar

Reputation: 4375

names = ['animals', 'nature', 'foodbev']  # dict's names
dict_of_dicts = {}

for name in names:
    dict_of_dicts[name] = Dictionary(k)

Upvotes: 0

Related Questions