打印词典内容

2024-06-13 12:58:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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}}

这是我为一个游戏创建的字典,当进入商店时,将在屏幕上打印十字轴以显示商店的内容。有没有办法让我从字典上印出来,上面写着斧头的名字和价格,最后还有硬币这个词。在

请记住,用户将选择他想要的斧头通过一个原始的输入,检查上面的字典,例如如果用户想要一个符文镐,他们会输入,它会检查是否在字典中,我不能在斧头的名字内加上价格。 铁镐-100个硬币


Tags: 用户字典价格硬币名字商店speedcost
2条回答

我想你想知道如何打印有关斧头的信息,也许下面的代码可以帮助你理解该怎么做,但是如果没有更多你尝试过的代码,很难给你一个有效的解决你自己问题的方法:

>>> 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

您可以这样简化此过程:

^{pr2}$

小贴士:

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

    '{name}: {value} coins'.format(name='adamant pickaxe', value=100)
    
  • 迭代Pickaxes.iteritems公司()获取所有元素:

    for name, properties in Pickaxes.iteritems():
        # do something with name and properties['cost']
    
  • ^{}函数将帮助您以特定的顺序遍历拾取轴。

相关问题 更多 >