0

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?

5
  • 1
    What is the expected output? A dict is an unordered data structure so I'm not sure why you'd want to do that
    – turtle
    Jan 14, 2021 at 17:21
  • 2
    What do you mean by first value? dict and set are not ordered, even though the dict in the latest versions of python3 is ordered by default. Jan 14, 2021 at 17:22
  • The expected output would be "some value", because of the "foo" on the set and on the dict
    – Rodrigo
    Jan 14, 2021 at 17:22
  • what's your expected output if bar was to be in d?
    – Tibebes. M
    Jan 14, 2021 at 17:30
  • 2
    Not just dict, set are also unordered. So you can never be sure what the first value will be. Jan 14, 2021 at 17:30

3 Answers 3

6

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)
3
  • 1
    maybe add None as the second argument to next to avoid a StopIteration error.
    – flakes
    Jan 14, 2021 at 17:28
  • 1
    @flakes, I've thought about that, but decided to leave it like it is, because I don't know exact values and it could cause logical mistakes if actual value will be None. Jan 14, 2021 at 17:30
  • 1
    Just for the sake of evil: next(filter(None, map(d.get, labels))) :^)
    – flakes
    Jan 14, 2021 at 17:40
1
for key in d:
    if key in labels:
        print(d[key])
        break
1

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
2
  • 2
    Would highly suggest using next here with a generator expression rather than creating a new list. That would avoid the possible index-out-of-bounds for no matches.
    – flakes
    Jan 14, 2021 at 17:25
  • 2
    Also use set notation: labels = {"foo", "bar"}
    – flakes
    Jan 14, 2021 at 17:26

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.