搜索列表上的值是否在格式为keystring、valuelist(strings)的字典中

2024-09-26 22:12:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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]

Tags: thekeyin列表dictionaryisvaluemy
1条回答
网友
1楼 · 发布于 2024-09-26 22:12:28

您还需要迭代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']

相关问题 更多 >

    热门问题