如何匹配列表中的键并找到相交的值?

时间:2014-10-14 03:31:27

标签: python string dictionary set

我有一个带有列表的字典,我的目标是将查询列表与字典匹配,并且匹配的术语显示相交的值。例如

  dict= [(this, ['1']), (word, ['1', '2']), (search, ['2'])]
  searchedQuery = [this, word]

  output = 1

有人能告诉我实施这种技术的最简单方法,我正在考虑使用这种方法

for key in dict.keys():
     ...get values 
     ...intersect values

3 个答案:

答案 0 :(得分:2)

像这样:

>>> d
[('this', ['1']), ('word', ['1', '2']), ('search', ['2'])]
>>> set.intersection(*[set(v) for k,v in d if k in searchedQuery])
set(['1'])

说明:

  • for k,v in d if k in searchedQuery枚举d中包含您想要的键
  • 的对
  • [set(v) ...]制作值集
  • 列表解析前面的
  • *解压缩列表,以便我们传递给set.intersection
  • set.intersection为您提供了交集。

旁白:

  • 正如另一个答案中所提到的,对的列表实际上不是dict
  • dict用于您自己的变量名称被认为不是一个好主意(但我们明白您的意思)。

答案 1 :(得分:1)

这个怎么样:

>>> dic = dict([('this', ['1']), ('word', ['1', '2']), ('search', ['2'])])
>>> searchedQuery = ['this', 'word']
>>> [y for x,y in dic.items() if x in searchedQuery]
[['1'], ['1', '2']]
>>>

答案 2 :(得分:1)

你可以做同样的事情。但是在进入它之前,你需要了解的东西很少。

Python中的字典,看起来像这样

d = {'this': ['1'], 'search': ['2'], 'word': ['1', '2']}

因此,为了获得您以字典形式呈现的数据,您需要执行类似的操作

d = [('this', ['1']), ('word', ['1', '2']), ('search', ['2'])]
print dict(item for item in d)

然后你可以从字典中获取对应于searchedQuery的值,最后像这样设置交集

print set.intersection(*[set(d.get(item, {})) for item in searchedQuery])
# set(['1'])