我怎么能按特定顺序打印这本字典?

时间:2015-09-11 04:15:48

标签: python python-3.x dictionary

LMTLabSep09

在我的编程课中,我们正在尝试制作基于文本的RPG。我们需要制作一个字典,然后使用一个列表,以便按特定顺序打印统计数据(顺序是列表中的顺序)。但是,我在使用" for循环"时遇到问题,并且统计数据继续在字典中打印,因此每次都以随机顺序打印。基本上我是在问我如何使用myList按照我想要的顺序打印统计数据?

from random import randint

def main():
#user input
name = input("Enter character name: ")
job = input("Enter character's job title: ")
age = eval(input("Enter character's age: "))
bckstry = input("Enter character's backstory: ")

#randomized stats
strength = randint (20, 30)
agility = randint (10, 20)
intel = randint (5, 50)

#character stats w/ formulas
health = strength * 10
mana = intel * 8
damage = agility * 6

#hero dictionary
myHero = {'name':name,
          'job':job,
          'age':age,
          'backstory':bckstry,
          'str':strength,
          'agi':agility,
          'int':intel,
          'health':health,
          'mana':mana,
          'dmg':damage}
print(myHero)

def callMyHero():
myHero = {'name':name,
          'job':job,
          'age':age,
          'backstory':bckstry,
          'str':strength,
          'agi':agility,
          'int':intel,
          'health':health,
          'mana':mana,
          'dmg':damage}

myList = ['name','job','age','backstory','str','agi','int','health','mana','dmg']

for i in range(0,len(myList)):
     print(myList[i])

main()
callMyHero()

1 个答案:

答案 0 :(得分:0)

您可能会发现这个问题对于您的字典以意外顺序打印的原因有用here。但要回答你的问题:

myList = ['name','job','age','backstory','str','agi','int','health','mana','dmg']
for key in myList:
    print myHero[key]