Reputation: 321
Let's suppose that I have the following set
:
labels = set(["foo", "bar"])
And I have a dict
with theses values
d = {
"foo": "some value",
"asdf": "another value",
}
How can I get the first value of the dictionary based on any value of the set labels
?
In other words, how can I get the value "some value" from the values of the set?
Upvotes: 0
Views: 1950
Reputation: 7812
You can apply next()
with generator expression:
result = next(d[k] for k in labels if k in d)
Upd. Code above works but it doesn't fit 100%, because it iterates over labels
and retrieve value of first key, which not always first occurrence.
To get value of first occurrence of any key from labels
use next code:
result = next(v for k, v in d.items() if k in labels)
Upvotes: 6
Reputation: 12347
Use list comprehension
and select the element with 0th index. You may want to wrap this in try...except
to catch the case where no element is found in the dictionary.
labels = set(["foo", "bar"])
d = {
"foo": "some value",
"asdf": "another value",
}
print([d[k] for k in labels if k in d][0])
# some value
Upvotes: 1