【问题标题】:How to print the key of a dictionary but not it's value? [python]如何打印字典的键而不是它的值? [Python]
【发布时间】:2017-09-23 14:32:21
【问题描述】:

我知道这可能非常简单,我忘记了一些东西,但我不记得如何打印字典的键。具体问题是我有一个可以攻击的动物部分的字典,值是用于攻击的动词,例如:{'teeth': 'bites'}

看起来像这样:

attack_part = random.choice(list(self.attacking_parts))

print('The', self.name, self.attacking_parts[attack_part], 'you with their', self.attacking_parts.keys() + '!')

但是当我使用它时会发生什么:

The bear scratches you with their scrathes!

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    您代码中的attack_part 变量是您的dict 的关键。当您执行self.attacking_parts[attack_part] 时,您正在获取与attack_part 键对应的值self.attacking_parts 字典。而self.attacking_parts.keys() 则返回字典中所有键的列表。

    因此,您应该使用 print 语句,例如:

    print('The', self.name, self.attacking_parts[attack_part], 'you with their', attack_part + '!')
    

    【讨论】:

      猜你喜欢
      • 2014-12-26
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-16
      相关资源
      最近更新 更多