Rodrigo
Rodrigo

Reputation: 321

Get first value in dict from a list of keys

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

Answers (3)

Olvin Roght
Olvin Roght

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

Timur Shtatland
Timur Shtatland

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

LightVillet
LightVillet

Reputation: 119

for key in d:
    if key in labels:
        print(d[key])
        break

Upvotes: 1

Related Questions