【发布时间】:2013-08-07 09:29:12
【问题描述】:
我有以下字典,其中的键对应于它在 Rock Paper Scissors Lizard Spock 规则内击败的值。因此。 “剪刀”击败“纸”和“蜥蜴”。
this_defeats_that = {'scissors': 'paper',
'paper': 'rock',
'rock': 'lizard',
'lizard': 'spock',
'spock': 'scissors',
'scissors': 'lizard',
'lizard': 'paper',
'paper': 'spock',
'spock': 'rock',
'rock': 'scissors'
}
但是,我发现当我
print this_defeats_that['scissors']
只打印“蜥蜴”。进一步的调查表明,无论我如何构建字典,打印语句都只会打印与给定键对应的最后一个值。
我需要的是打印所有相关的值,以便
# Example, this behavior should be consistent regardless of key.
print this_defeats_that['scissors']
将以任意顺序打印“蜥蜴”和“纸”。最好以列表形式返回。
所以我尝试了一个列表理解,
print [value for key, value in this_defeats_that.iteritems() if key == 'scissors']
但它也只返回与键对应的最后一个值,即“蜥蜴”。 我现在不知道该怎么做,急需帮助。
【问题讨论】:
标签: python dictionary key key-value