2016-05-06 63 views
-1
self.biography = {'name' : '', 'age' : 0, 'nationality' : '', 'position' : '', 'footed' : ''} 

    def create_player(self): 
     name = input('Player name: ') 
     age = int(input('Player age: ')) 
     nationality = input('Nationality: ') 
     position = input('Position: ') 
     footed = input('Footed: ') 
     bio_attributes = [name, age, nationality, position, footed] 
     for attribute in bio_attributes: 
      self.biography[attribute] = bio_attributes 

我有點想通過這條巨蟒方法進行迭代,然後將值到詞典中,我知道我可以做類似遍歷用戶輸入和插入到Python字典

self.biography["name"] = name 
self.biography["age"] = age 

但這顯然重複的代碼,所以我如何使用像我的循環,使這項工作?

+3

我已經回答了http://stackoverflow.com/questions/37069871/append-to-python-dictionary-from-method/37069996#37069996 –

回答

0

你的意思是這樣的嗎?

self.biography = {'Player name' : '', 'Player age' : 0, 'Nationality' : '', 'Position' : '', 'Footed' : ''} 
def create_player(self): 
    for key in self.biography: 
     val = input(key + ': ') 
     self.biography[key] = val