Append to Python dictionary from method

前端 未结 3 592
终归单人心
终归单人心 2021-01-27 12:27

I have this dictionary called biography

self.biography = {\'Name\' : \'\', \'Age\' : 0, \'Nationality\' : \'\', \'Position\' : 0, \'Footed\' : \'\'}
3条回答
  •  日久生厌
    2021-01-27 13:12

    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 ...
    

    Just access your biography dict like an (associative) array.
    If you want an ordered output, use an OrderedDict like so:

    from collections import OrderedDict
    
    class myClass():
        biography = OrderedDict()
        def setupDict(self):
            self.biography["Name"] = "Some name here"
    

提交回复
热议问题