在Python中相交两个字典 [英] Intersecting two dictionaries in Python

查看:149
本文介绍了在Python中相交两个字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过一个倒排的索引来搜索一个搜索程序。索引本身是一个字典,其键是术语,其值本身是短文档的字典,ID号作为键,其文本内容作为值。



为了执行两个术语的和搜索,我需要与他们的贴子列表(词典)相交。什么是明确的(不一定是过分聪明的)在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆