[英]How to find all keys within a dictionary which contains only ALL values from a list
i'am new in python. 我是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. 使用此示例,我想获得的只是键“ lara”,这是唯一包含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
使用列表理解和
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). 使用列表或字典理解来过滤字典中的元素(以下将
dict
重命名为dikt
以避免与dict
类冲突)。 The all
function returns True
if all elements of the iterable are True
. 在
all
函数返回True
,如果迭代的所有元素都是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 使用
set.isubset
方法查找给定集合是否为列表的子集
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)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.