NewUser123 NewUser123 - 7 months ago 8
Python Question

Append to Python dictionary from method

I have this dictionary called biography

self.biography = {'Name' : '', 'Age' : 0, 'Nationality' : '', 'Position' : 0, 'Footed' : ''}


I also have this method called create_player

def create_player(self):
name = input('Player name: ')
age = int(input('Player age: '))
nationality = input('Nationality: ')
position = input('Position: ')
footed = input('Footed: ')


How can I go through this list and append to biography dictionary, matching up the various attribute names with their values accordingly

Jan Jan
Answer
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"