首页 > 解决方案 > 如果字典中的两个值属于同一个键,它们是否属于另一个字典中的同一个键?

问题描述

我正在尝试与两个字典进行比较以检查大数据集的准确性

我想看看两个点是否属于字典 1 中的同一个键,它们属于字典 2 中的同一个键

我有办法用“如果两个字典中的点”做一个双循环我正在寻找一种更快的方法来比较两个字典

dict_1 每个 point_id 只有 1 个键,其中 dict_2 可以有 1 个 point_id 的多个键

两个字典看起来像:

{key1 : [list of point id], key2 : [list of point id], etc}

dict_1 = {key1 : [1,2,3,4,5,6], key2 : [7,8,9,10,11,12]}  
dict_2 = {key3 : [1,2,4,6,8,11,12], key4 :[2,5,7,9,10,11,12]}

def accuracy_from_dict_to_dict(dict_1,dict_2):
    total, truth = 0,0
    for key_dict_1 in dict_1:
        point_of_key = dict_1.get(key_dict_1)
        i=0
        while i < len(point_of_key): #for each point of the key_dict_1 list
          j = i+1
          while j < len(point of key):
              for key_dict_2 in dict_2:
                  point_i = point_of_key[i]
                  point_j = point_of_key[j]
                  if point_i in key_dict_2 and point_j in key_dict_2:
                      truth += 1
                  total += 1
                  j += 1  
          i+=1

问题不在于代码本身,而在于计算时间。除非数据集足够小,否则运行时间太长

标签: pythondictionarycompare

解决方案


看起来您只是在检查两个字典中的 2 项组合。您可以使用标准库中的itertools模块做得更好:

from itertools import combinations, chain

dict_1 = {'key1' : [1,2,3,4,5,6], 'key2' : [7,8,9,10,11,12]}  
dict_2 = {'key3' : [1,2,4,6,8,11,12], 'key4' :[2,5,7,9,10,11,12]}

c_dict1 = set(chain.from_iterable(combinations(v, 2) for v in dict_1.values()))
c_dict2 = set(chain.from_iterable(combinations(v, 2) for v in dict_2.values()))
total = len(c_dict1) + len(c_dict2)
similarity = len(c_dict1 & c_dict2) / total
print(total, similarity)

将打印您:

69 0.2753623188405797


推荐阅读