i'am new in python. I Am currently working on a script that filters job applicants by which programing languages they use. I've a dictionary containing each candidate (keys) and her language (value). I want to find ONLY the keys within a dictionary whose values contains ALL items contained in a list. For example:
list1 = ['php', 'net']
dict = {
'lara': ['net', 'php', 'python'],
'john': ['php', 'c++'],
'ian' : ['php','python']}
Using this example what i want to get would be only the key 'lara', which is the only one containing all the values listed within list1. I've searched like mad for a solution to this problem but so far i've found nothing around and neither could make it work for myself.
Any help will be welcome
Using a list comprehension and all
list1 = ['php', 'net']
d = {'lara': ['net', 'php', 'python'], 'john': ['php', 'c++'], 'ian': ['php','python']}
print([k for k,v in d.items() if all(i in v for i in list1)])
Output:
['lara']
Expanded version.
res = []
for k,v in d.items():
if all(i in v for i in list1):
res.append(k)
Use a list or dict comprehension to filter the elements in the dictionary (renamed dict
to dikt
below to avoid clashing with the dict
class). The all
function returns True
if all elements of the iterable are True
.
list1 = ['php', 'net']
dikt = {'lara': ['net', 'php', 'python'], 'john': ['php', 'c++'], 'ian': ['php','python']}
# Matching keys as a list:
[k for k,v in dikt.items() if all(x in v for x in list1)]
# ['lara']
# Matching entries returned as a dict:
{k:v for k,v in dikt.items() if all(x in v for x in list1)}
# {'lara': ['net', 'php', 'python']}
Use set.isubset
method to find if the given set is subset of the lists
list1=['php', 'net']
dict1={'lara': ['net', 'php', 'python'], 'john': ['php', 'c++'], 'ian': ['php','python']}
set1=set(list1)
{k:v for k,v in dict1.items() if set1.issubset(v)}
# {'lara': ['net', 'php', 'python']}
Use sets instead of lists.
set1 = {'php', 'net'}
dict1 = {'lara': ['net', 'php', 'python'], 'john': ['php', 'c++'], 'ian': ['php','python']}
{k: v for k,v in dict1.items() if set1.issubset(v)}
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.