簡體   English   中英

如何打印字典的鍵但不是它的值? [蟒蛇]

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM