2017-10-24 2 views
0

스페인어 단어와 정의로 채워진 다른 사전을로드 할 수있는 콘솔 응용 프로그램을 만들고 있습니다.이 모듈에서 내 사전 클래스의 모든 개체를 만들고 싶습니다. 하나의 dict_of_는 main.py에 들어갑니다. 대신과 같이 각 인스턴스 각각의 객체를 쓰는 :파이썬 사전 개체 인스턴스화 NameError

animals_dict = Dictionary('animals') 

내 dict_of_dicts을 통해 루프 싶었을 만들 수 있습니다. 이제 내가이 작업을 수행 할 때 NameError가 발생합니다. 왜냐하면이 객체는 아직 정의되지 않았기 때문에 생각할 수 있습니다.하지만이 객체를 순차적으로 작성하는 대신 루프로 작성하는 작업이 있는지 궁금합니다. .

# 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 

답변

1

당신은 당신이 그 이상 루프

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

을 새 사전을 만들거나 이해로

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

할 수 ['animals', 'nature', 'irregulars'] #etc

이름의 목록이 있다고 가정 대상 외에 아직 존재하지 않는다면 다른 문제는 dict.items을 통해 사전 항목을 반복 할 때 해당 이름에 대한 할당을 실제로 수행해도 사전이 수정되지 않는다는 것입니다.

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 
0
names = ['animals', 'nature', 'foodbev'] # dict's names 
dict_of_dicts = {} 

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

또는 (Python 2.6 이상이라고 가정),'dict_of_dicts = {name : 이름의 이름에 대한 사전 (name)}' – DeepSpace