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 Commented 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. Commented Jan 14, 2021 at 17:22
  • The expected output would be "some value", because of the "foo" on the set and on the dict Commented Jan 14, 2021 at 17:22
  • what's your expected output if bar was to be in d? Commented 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. Commented Jan 14, 2021 at 17:30

3 Answers 3

7

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) 
Sign up to request clarification or add additional context in comments.

3 Comments

maybe add None as the second argument to next to avoid a StopIteration error.
@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.
Just for the sake of evil: next(filter(None, map(d.get, labels))) :^)
1
for key in d: if key in labels: print(d[key]) break 

Comments

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 Comments

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.
Also use set notation: labels = {"foo", "bar"}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.