如何打印字典的键而不是它的值?[Python]

2024-05-20 21:00:16 发布

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

我知道这可能是非常简单,我忘了一些东西,但我不记得如何打印字典的关键。具体的问题是我有一本字典,里面有动物可以攻击的部分,值是用来攻击的动词,例如:{tooth':'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!

Tags: theselfyou字典biteswith动词关键
1条回答
网友
1楼 · 发布于 2024-05-20 21:00:16

代码中的attack_part变量是dict的键。在执行self.attacking_parts[attack_part]时,将获取与self.attacking_partsdict中的attack_part键对应的值,而执行self.attacking_parts.keys()将返回dict中存在的所有键的列表

因此,您应该使用如下打印语句:

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

相关问题 更多 >