Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python get dictionary values list as list if key match

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading