如何打印字典的键但不是它的值? [python]
问题描述:
我知道这可能非常简单,我忘了一些东西,但我不记得如何打印字典的关键。具体问题是我有一个动物的部分可以攻击的字典,值是用来攻击,如动词:{“牙齿”:“咬”}如何打印字典的键但不是它的值? [python]
它看起来像这样:
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!
答
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 + '!')