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
Solution 1:
defcreate_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: ')
try this.
Solution 2:
defcreate_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
Solution 3:
defcreate_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
classmyClass():
biography =OrderedDict()
def setupDict(self):
self.biography["Name"] ="Some name here"
Post a Comment for "Append To Python Dictionary From Method"