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, ie, :
tarfiles = ['tar3', 'tar5']
How can I get it?
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]
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.