简体   繁体   中英

Python: Return all values that corresponds to a given key inside a dictionary

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, ie 'lizard'. I'm now clueless as to how to proceed, and am in dire need of help.

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']

Why don't you group the ones with a single key into a list?

Eg)

this_defeats_that = {'scissors': ['paper' , 'lizard'] , 'paper': ['rock', 'spock' ] 
    ...}

And to retrive,

for i in this_defeats_that['scissors']:
    print i

This does the trick

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM