打印字典内容

时间:2013-12-23 15:30:52

标签: python dictionary

Pickaxes = {
 'adamant pickaxe': {'cost': 100, 'speed': 5},
 'bronze pickaxe': {'cost': 100, 'speed': 5},
 'dragon pickaxe': {'cost': 100, 'speed': 5},
 'inferno adze': {'cost': 100, 'speed': 5},
 'iron pickaxe': {'cost': 100, 'speed': 5},
 'mithril pickaxe': {'cost': 100, 'speed': 5},
 'rune pickaxe': {'cost': 100, 'speed': 5},
 'steel pickaxe': {'cost': 100, 'speed': 5}}

这是我为游戏创建的词典,当进入商店时,镐将被打印在屏幕上以显示商店的内容。有没有什么方法我可以从字典中打印出来,显示斧头的名称和PRICE,最后还有COINS这样的字样。

PS。请记住,用户将通过raw_input选择他想要的内容,该raw_input检查字典上面,例如,如果用户想要一个符文镐,他们会输入它并检查它是否在字典中我无法添加斧头本身的价格。     坚定的镐 - 100枚硬币

2 个答案:

答案 0 :(得分:2)

提示:

  • 使用格式字符串获得一个很好的描述:

    '{name}: {value} coins'.format(name='adamant pickaxe', value=100)
    
  • 遍历Pickaxes.iteritems()以获取所有元素:

    for name, properties in Pickaxes.iteritems():
        # do something with name and properties['cost']
    
  • sorted函数将帮助您按特定顺序迭代您的镐。

答案 1 :(得分:0)

我想您想知道如何打印有关斧头的信息,也许以下代码可以帮助您了解要做什么,但如果没有更多的代码,您尝试过,很难为您提供有效的解决方案对你自己的问题:

>>> Pickaxes = {
 'adamant pickaxe': {'cost': 100, 'speed': 5},
 'bronze pickaxe': {'cost': 100, 'speed': 5},
 'dragon pickaxe': {'cost': 100, 'speed': 5},
 'inferno adze': {'cost': 100, 'speed': 5},
 'iron pickaxe': {'cost': 100, 'speed': 5},
 'mithril pickaxe': {'cost': 100, 'speed': 5},
 'rune pickaxe': {'cost': 100, 'speed': 5},
 'steel pickaxe': {'cost': 100, 'speed': 5}}

>>> for axe, values in Pickaxes.items():
    print '{} - costs: {}, speed: {}'.format(axe, values['cost'], values['speed'])

bronze pickaxe - costs: 100, speed: 5
mithril pickaxe - costs: 100, speed: 5
adamant pickaxe - costs: 100, speed: 5
steel pickaxe - costs: 100, speed: 5
iron pickaxe - costs: 100, speed: 5
rune pickaxe - costs: 100, speed: 5
dragon pickaxe - costs: 100, speed: 5
inferno adze - costs: 100, speed: 5

您可以像这样简化此过程:

>>> Pickaxes = {
 'adamant pickaxe': {'name': 'adamant pickaxe', 'cost': 100, 'speed': 5},
 'bronze pickaxe': {'name': 'bronze pickaxe', 'cost': 100, 'speed': 5},
 'dragon pickaxe': {'name': 'dragon pickaxe', 'cost': 100, 'speed': 5},
 'inferno adze': {'name': 'inferno pickaxe', 'cost': 100, 'speed': 5},
 'iron pickaxe': {'name': 'iron pickaxe', 'cost': 100, 'speed': 5},
 'mithril pickaxe': {'name': 'mithril pickaxe', 'cost': 100, 'speed': 5},
 'rune pickaxe': {'name': 'rune pickaxe', 'cost': 100, 'speed': 5},
 'steel pickaxe': {'name': 'steel pickaxe', 'cost': 100, 'speed': 5}}

>>> for axe in Pickaxes.values():
    print '{name} - costs: {cost}, speed: {speed}'.format(**axe)


bronze pickaxe - costs: 100, speed: 5
mithril pickaxe - costs: 100, speed: 5
adamant pickaxe - costs: 100, speed: 5
steel pickaxe - costs: 100, speed: 5
iron pickaxe - costs: 100, speed: 5
rune pickaxe - costs: 100, speed: 5
dragon pickaxe - costs: 100, speed: 5
inferno pickaxe - costs: 100, speed: 5