[英]How to print the key of a dictionary but not it's value? [python]
我知道這可能非常簡單,並且我忘記了一些東西,但是我不記得如何打印字典的鍵。 具體的問題是我有一個可以攻擊的動物部分字典,其值是用於攻擊的動詞,例如:{'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!
代碼中的attack_part
變量是dict
的關鍵。 在執行self.attacking_parts[attack_part]
,您將在self.attacking_parts
字典中獲取與attack_part
密鑰相對應的值。 而self.attacking_parts.keys()
返回字典中存在的所有鍵的列表。
因此,您應該使用如下打印語句:
print('The', self.name, self.attacking_parts[attack_part], 'you with their', attack_part + '!')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.