my_dict = { # This dictionary is generated thru
'a' : [ 'value1', 'value4', 'value5' ], # the info given by the user
'b' : [ 'value2', 'value6', 'value7'],
'c' : [ 'value3', 'value8', 'value9']
}
list = [ 'value1', 'value2' ] # List is generated using list comprehension
我需要生成一个输出如下内容的列表:
output_list = ['a', 'b']
我需要检查“list”上的值是否与字典中列表上的值匹配。这有可能吗?你知道吗
我试着用这个,但我只得到一个空列表:
[key for key, value in my_dict.items() if value in list]
您还需要迭代
list
(您不应该使用list
作为变量名,它会隐藏内置的list
函数)。示例-演示-
如果使用
set
而不是list
在字典中存储值,则可以获得更好的性能(因为在集合内搜索是O(1)操作,而在列表内搜索是O(n))。示例-演示-
如果要检查列表中的任何值是否与字典中列表中的任何值匹配,可以使用
set.intersection
并检查结果是否为空。示例-这个结果不会被排序,因为字典没有任何特定的顺序。你知道吗
演示-
相关问题 更多 >
编程相关推荐