What's the most elegant way to check if at least one specific value exists within a dictionary out of a list of 'targets'? I've been using or statements in the past, but these can be fairly lengthy:
d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
if 'six' in d.values() or 'eight' in d.values() or 'ten' in d.values() or 'fifteen' in d.values():
# do something
else:
# do something else
Is it better to create a list of targets, then loop through that list to check each against the dictionary individually? In that case, I'd also need to put breaks at the end of the if/else blocks to ensure it's not triggered multiple times:
targets = ['six', 'eight', 'ten', 'fifteen']
d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
for t in targets:
if t in d.values():
# do something
break # to ensure the thing isn't triggered multiple times
else:
# do something else
break # to ensure the thing isn't triggered multiple times
Is there a recommended way to shorten this, or is the 2nd code block as good as it gets?
question from:
https://stackoverflow.com/questions/65891631/check-if-dictionary-contains-at-least-one-specific-value-out-of-a-list 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…