简体   繁体   中英

find out which list contains a value in a dictionary

I have written a chess program and are currently working my way through coding check. How can I work out which piece (key in the dictionary) has kingpos in their list?

The example below should give an answer of 'ksbishop' .

kingpos=(5,1)
movesdict={'ksknight': [(8, 3), (5, 2), (6, 3)],
 'ksbishop': [(3, 6), (4, 7), (5, 8), (1, 4), (1, 6), (3, 4), (4, 3), (5, 1), (6, 1)],
 'king': [(6, 1), (5, 2), (4, 1)],
 'queen': [(4, 5), (2, 4), (1, 3), (2, 6), (1, 7), (4, 4)],
 'qsknight': [(3, 3), (1, 3)]}
if kingpos in [z for v in movesdict.values() for z in v]:
# find out which key has it 

You can use a list comprehension:

>>> [key for key in movesdict if kingpos in movesdict[key]]
['ksbishop']

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