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']
我需要检查“列表”上的值是否与字典内列表上的值匹配。这有可能吗?
我尝试使用此方法,但只得到一个空列表:
[key for key, value in my_dict.items() if value in list]
您还需要遍历list
(并且您不应该将其list
用作变量名,它会掩盖内置list
函数)。范例-
[key for item in lst for key,value in my_dict.items() if item in value]
演示-
>>> 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']
... }
>>>
>>> lst = [ 'value1', 'value2' ]
>>> [key for item in lst for key,value in my_dict.items() if item in value]
['a', 'b']
如果使用set
而不是list
将值存储在字典中,则可以获得更好的性能(因为在集合内部进行搜索是O(1)运算,而在列表内部进行搜索是O(n))。范例-
my_dict = {key:set(value) for key,value in my_dict.items()}
[key for item in lst for key,value in my_dict.items() if item in value]
演示-
>>> my_dict = {key:set(value) for key,value in my_dict.items()}
>>> pprint(my_dict)
{'a': {'value4', 'value5', 'value1'},
'b': {'value6', 'value7', 'value2'},
'c': {'value3', 'value9', 'value8'}}
>>> lst = [ 'value1', 'value2' ]
>>> [key for item in lst for key,value in my_dict.items() if item in value]
['a', 'b']
如果您要检查列表中的任何值是否与字典中列表中的任何值匹配,则可以使用set.intersection
并检查结果是否为空。范例-
[key for key, value in my_dict.items() if set(value).intersection(lst)]
由于字典没有任何特定顺序,因此该结果将不会排序。
演示-
>>> my_dict = {
... 'a' : [ 'value1', 'value4', 'value5' ],
... 'b' : [ 'value2', 'value6', 'value7'],
... 'c' : [ 'value3', 'value8', 'value9']
... }
>>> lst = [ 'value1', 'value2' ]
>>> [key for key, value in my_dict.items() if set(value).intersection(lst)]
['b', 'a']
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句