Python: Return all values that corresponds to a given key inside a dictionary
dictionary, key, key-value, python
Solution
You have to change the way you store the mapping. Dictionary in python is a key:value mapping, keys are unique.
Consider making a list of values for each unique key instead:
>>> this_defeats_that = {'scissors': ['paper', 'lizard'],
'paper': ['rock', 'spock'],
'lizard': ['spock', 'paper'],
'spock': ['scissors', 'rock'],
'rock': ['scissors', 'lizard']}
>>> this_defeats_that['scissors']
['paper', 'lizard']
Problem
I have the following dictionary, where the key of which corresponds to a value which inside of the rules of Rock Paper Scissors Lizard Spock it defeats. Ergo. 'scissors' defeats 'paper' and 'lizard'. ``` this_defeats_that = {'scissors': 'paper', 'paper': 'rock', 'rock': 'lizard', 'lizard': 'spock', 'spock': 'scissors', 'scissors': 'lizard', 'lizard': 'paper', 'paper': 'spock', 'spock': 'rock', 'rock': 'scissors' } ``` However, I find that when I ``` print this_defeats_that['scissors'] ``` only 'lizard' is printed. Further investigation has shown me that, regardless of how I structure the dictionary, the print statement will only print the value that is the last value corresponding to the given key. What I need is for it to print is all the related values so that ``` # Example, this behavior should be consistent regardless of key. print this_defeats_that['scissors'] ``` will print 'lizard' and 'paper' in any order. Preferably returned as a list. And so I attempted a list comprehension, ``` print [value for key, value in this_defeats_that.iteritems() if key == 'scissors'] ``` but it too only returns the last value which corresponds to the key, i.e. 'lizard'. I'm now clueless as to how to proceed, and am in dire need of help.