迭代用户输入并插入python字典

时间:2016-05-06 12:02:11

标签: python for-loop dictionary

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

但这显然是在重复代码,所以我怎样才能使用像我的for循环这样的工作呢?

1 个答案:

答案 0 :(得分: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