【问题标题】:Searching if the values on a list is in the dictionary whose format is key-string, value-list(strings)搜索列表中的值是否在格式为 key-string, value-list(strings) 的字典中
【发布时间】:2023-03-20 17:09:02
【问题描述】:
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]

【问题讨论】:

  • 你的理解评估为if [ 'value1', 'value4', 'value5' ] in list btw
  • 感谢伊恩的评论!

标签: python list python-3.x dictionary


【解决方案1】:

您还需要遍历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']

【讨论】:

  • 库马尔先生,您好!非常感谢您的回复。有效。我只是不明白你所说的设置的 O(1) 操作和列表的 O(n) 操作是什么意思。请赐教。我仍然是 Python 的新手。谢谢!
  • O(1) 操作意味着它将在恒定时间内完成,在集合中搜索项目所需的时间与集合的大小无关。与 O(n) 相比,O(n) 意味着在列表中搜索项目所需的时间取决于列表的大小,因此随着大小的增加,搜索其中的项目将花费更多时间。
  • 哇。这意味着很多。谢谢你。我可以在这里就代码做一个后续问题吗?如果我有一个需要与字典中列表中的值进行比较的字符串而不是列表,该怎么办?
  • 你需要如何比较字符串的值?我的意思是字符串的示例以及您期望的输出。
  • 库马尔先生,我想通了。与上面相同的输出。一个列表,其中包含与用户输入包含相同字符串值的所有键。我用了这个:[key for key, value in my_dict.items() if user_input in value]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多