-3

I have the following list and dictionary:

match_keys = ['61df50b6-3b50-4f22-a175-404089b2ec4f']

locations = {
  '2c50b449-416e-456a-bde6-c469698c5f7': ['422fe2d0-b10f-446d-ac3c-f75e5a3ff138'], 
  '61df50b6-3b50-4f22-a175-404089b2ec4f': [
   '7112fa59-63b1-4057-8822-fe11168c328f', '6d06ee0a-7447-4726-822f-942b9e12c9ce'
   ]
}

If I want to search 'locations' for keys that match in the match_keys list and extract their values, to get something like this...

['7112fa59-63b1-4057-8822-fe11168c328f', '6d06ee0a-7447-4726-822f-942b9e12c9ce']

...what would be the best way?

Mark R
  • 137
  • 1
  • 8
  • I'm not following what the problem is here. Are you looking for a plain key lookup, i.e. ``locations[match_keys[0]]``? – MisterMiyagi Jan 24 '22 at 09:08
  • So for each key match find their corresponding values in the dictionary locations. – Mark R Jan 24 '22 at 09:10
  • Okay, and what about it is the problem you are asking here? There's only a single key and a single result list in your example, so it's hard to say what needs solving here. Do you have very many keys to look up and cannot do it sequentially? Is there some efficiency consideration, such as most keys not being in the dict? Some post-processing challenge, such as flattening the results or eliminating duplicates? – MisterMiyagi Jan 24 '22 at 09:18

3 Answers3

1

You can iterate over match_keys and use dict.get to get the values under each key:

out = [v for key in match_keys if key in locations for v in locations[key]]

Output:

['7112fa59-63b1-4057-8822-fe11168c328f', '6d06ee0a-7447-4726-822f-942b9e12c9ce']
  • Thanks. I get a list of list. [['7112fa59-63b1-4057-8822-fe11168c328f', '6d06ee0a-7447-4726-822f-942b9e12c9ce']] Is there a way just to have the one list. ['7112fa59-63b1-4057-8822-fe11168c328f', '6d06ee0a-7447-4726-822f-942b9e12c9ce'] – Mark R Jan 24 '22 at 09:17
  • This will fail with an error if the key is not in the dict. – MisterMiyagi Jan 24 '22 at 09:20
  • I think for the intended purposes, the key will always be in the dict. – Mark R Jan 24 '22 at 09:23
  • 1
    @MarkR That's important information which should be in the question, not some answer comment. – MisterMiyagi Jan 24 '22 at 09:24
0
for key, value in locations.items():
    if key == match_keys[0]:
        print(value)
Erik
  • 59
  • 1
  • 8
0

Iterate over keys and get value by [].

res = []
for key in matched_keys:
  res.append(matched_keys[key])

or if you dont want list of lists you can use extend()

res = []
for key in matched_keys:
  res.extend(matched_keys[key])
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
Tomáš Šturm
  • 489
  • 4
  • 8