我有这本名为传记的词典
self.biography = {'Name' : '', 'Age' : 0, 'Nationality' : '', 'Position' : 0, 'Footed' : ''}
我也有这个叫做create_player
的方法def create_player(self):
name = input('Player name: ')
age = int(input('Player age: '))
nationality = input('Nationality: ')
position = input('Position: ')
footed = input('Footed: ')
如何浏览此列表并附加到传记字典中,相应地将各种属性名称与其值相匹配
答案 0 :(得分:1)
def create_player(self):
for key in self.biography.keys():
val = input('Player {}: '.format(key.lower()))
self.biography[key] = int(val) if val.strip().isdigit() else val
答案 1 :(得分:1)
def create_player(self):
self.biography['Name'] = input('Player name: ')
self.biography['Age'] = int(input('Player age: '))
self.biography['Nationality'] = input('Nationality: ')
self.biography['Position'] = input('Position: ')
self.biography['Footed'] = input('Footed: ')
试试这个。
答案 2 :(得分:0)
def create_player(self):
name = input('Player name: ')
age = int(input('Player age: '))
nationality = input('Nationality: ')
position = input('Position: ')
footed = input('Footed: ')
# afterwards
self.biography["Name"] = name
self.biography["Age"] = age
... and so on ...
只需访问biography
dict,就像(关联)数组一样
如果您想要有序输出,请使用OrderedDict
,如下所示:
from collections import OrderedDict
class myClass():
biography = OrderedDict()
def setupDict(self):
self.biography["Name"] = "Some name here"