从方法追加到Python字典 [英] Append to Python dictionary from method
本文介绍了从方法追加到Python字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这本叫做传记的字典
I have this dictionary called biography
self.biography = {'Name' : '', 'Age' : 0, 'Nationality' : '', 'Position' : 0, 'Footed' : ''}
我也有一个叫做create_player的方法
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
推荐答案
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
字典.
如果需要有序的输出,请使用 OrderedDict
所以:
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"
这篇关于从方法追加到Python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文