Python 将列表与具有多个值的字典进行比较并返回匹配项
如果我此列表:
list1 = ['a long way home she said', 'amazing grace for me', 'shes super cool']
我想将列表1中的每个项目与下面的dict1中的值进行比较:
dict1 = {
'Formula1': ('a long way home', 'nothing to see here'),
'Formula 2': ('nasty girl', 'nope'),
'Formula 3': ('disguisting', 'nope'),
'Formula 4': ('amazing grace', 'hello world')
}
如何使输出从list1中的整个匹配短语返回dict1的键?
所需的输出将是:
['formula1':('漫长的回家她说的'),'公式4':(对我来说,'Amazing Grace')]或
{'formula1 ':('漫长的回家她说的'),“公式4” :(对我来说,“惊人的恩典”)}
我试图这样做:
导入itertools
代码> [x如果不是x in itertools.chain(dict1.values())else [dict1中的键的键是否在list1中的x中值[key]] [0] 中
,但我认为我的输出实际上,在迭代字典值之后,它只是要返回列表中的所有内容。我有数百万个记录可以通过,因此列表理解比循环更可取。
[name in name,title in dict1.items()中的标题()如果所有(list1中的x中的x in title in list1中的x中的x)]
这只是返回一个空列表
If I this list:
list1 = ['a long way home she said', 'amazing grace for me', 'shes super cool']
I want to compare each item in list 1 to the values in dict1 below:
dict1 = {
'Formula1': ('a long way home', 'nothing to see here'),
'Formula 2': ('nasty girl', 'nope'),
'Formula 3': ('disguisting', 'nope'),
'Formula 4': ('amazing grace', 'hello world')
}
How can I get the output to return the key from dict1 with the entire matching phrase in list1?
The desired output would be:
['Formula1': ('a long way home she said'), 'Formula 4': ('amazing grace for me')] or
{'Formula1': ('a long way home she said'), 'Formula 4': ('amazing grace for me')}
I was trying to do this like so:
import itertools
[x if not x in itertools.chain(dict1.values()) else [key for key in dict1 if value in dict[key]][0] for x in list1]
But I think my output is actually just going to return everything in the list after iterating through dictionary values. I have millions of records to go through so list comprehension is preferable to a loop.
[name for name, title in dict1.items() if all(x in title for x in list1)]
This just returned an empty list
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于字典中的每个键,创建一个新的元组。对于
list1
中的每个元素,如果在原始元组值中存在一个字符串,该字符串是该元素的子字符串,则将其保留在结果中。存储此计算的结果(在下面的代码段中,我们将其存储在evers
变量中)。然后,我们滤除所有使用字典理解的空元组的键值对。您可以将其凝结成一条线,但是我认为那时它变得不可读:
这是输出的:
For each key in the dictionary, create a new tuple. For every element in
list1
, if there exists a string in the original tuple value that is a substring of that element, then retain it in the result. Store the result of this computation (in the below code snippet, we store it in thephrases
variable).Then, we filter out all of the key-value pairs that have empty tuples for values using a dictionary comprehension. You could condense this into one line, but I think it becomes pretty unreadable at that point:
This outputs: