在Python中相交两个字典 [英] Intersecting two dictionaries in Python
问题描述
为了执行两个术语的和搜索,我需要与他们的贴子列表(词典)相交。什么是明确的(不一定是过分聪明的)在Python中这样做?我开始尝试了很多的方式与 iter
:
p1 = index [term1]
p2 = index [term2]
i1 = iter(p1)
i2 = iter(p2)
while ...#不确定' != end'语法在这种情况下
...
您可以轻松计算交集,从而创建密钥集,并将其用于交集:
keys_a = set(dict_a.keys())
keys_b = set(dict_b.keys())
intersection = keys_a& keys_b#'&'运算符用于集合交集
I am working on a search program over an inverted index. The index itself is a dictionary whose keys are terms and whose values are themselves dictionaries of short documents, with ID numbers as keys and their text content as values.
To perform an 'AND' search for two terms, I thus need to intersect their postings lists (dictionaries). What is a clear (not necessarily overly clever) way to do this in Python? I started out by trying it the long way with iter
:
p1 = index[term1]
p2 = index[term2]
i1 = iter(p1)
i2 = iter(p2)
while ... # not sure of the 'iter != end 'syntax in this case
...
You can easily calculate the intersection of sets, so create sets from the keys and use them for the intersection:
keys_a = set(dict_a.keys())
keys_b = set(dict_b.keys())
intersection = keys_a & keys_b # '&' operator is used for set intersection
这篇关于在Python中相交两个字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!