Home > Blockchain >  python get dictionary values list as list if key match
python get dictionary values list as list if key match

Time:01-24

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?

CodePudding user response:

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']

CodePudding user response:

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])

CodePudding user response:

for key, value in locations.items():
    if key == match_keys[0]:
        print(value)
  •  Tags:  
  • Related