Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

python - Check if dictionary contains at least one specific value out of a list

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can replace it with the next one:

if any(t in d.values() for t in targets):
    pass
else:
    pass

In some cases will be better to convert d.values() into set and pass to the additional variable.

values = set(d.values())

if any(t in values for t in targets):
    # ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...