Home > Back-end >  Get value from dict where key is value another list
Get value from dict where key is value another list

Time:12-15

I want to extract the value from dict where key matches another list

l_dict = {"oc1":"tar1", "oc2":"tar2", "oc3":"tar3", "oc4":"tar4","oc5":"tar5"}
l_list = ["oc3", "oc5"] 

ld = set(l_dict)
ll = set(l_list)

for i in ld.intersection(ll):
    print("Element " i " was found") 

I get :

Element oc3 was found. 
Element oc5 was found. 

I really need an output with tar values from dict, i.e, :

tarfiles = ['tar3', 'tar5']

How can I get it?

CodePudding user response:

Instead of printing, save the corresponding value

tars = []
for i in ld.intersection(ll):
    tars.append(l_dict[i])

Note that is all strings from l_list are keys of l_dict just do

tars = [l_dict[key] for key in l_list]

CodePudding user response:

tarfiles = [l_dict[key] for key in l_list]

if there are items in l_list that are not keys in l_dict use:

tarfiles = [l_dict[key] for key in l_list if key in l_dict]
  • Related