比较2个字典列表中值的[1:]元素的最快方法

时间:2016-06-20 06:01:48

标签: python performance dictionary comparison

我有以下两个庞大的词典:

Dic1={0:['F','15','O+','5'],1:['M','12','O+'],2:[F,'20','O-'],3:['F','10','A+'],4:['M','45','?']...}

Dic2={0:['M','15','O+','5'],1:['M','12','O+'],2:[F,'20','A-'],3:['F','10','A+'],4:['F','15','?'],5:['M','10','A+']...}

我需要比较两者以找到两个字典中相同的V [1:],以便将它们组合在一个字典中并从另一个字典中删除该值。

新Dic1:

Dic1={0:['F,M','15','O+','5'],1:['2M','12','O+'],2:[F,'20','O-'],3:['2F,M','10','A+'],4:['M','45','?']...}

新Dic2:

Dic2={2:[F,'20','A-'],4:['F','15','?'],...}

我到目前为止的想法是:

for ((key1, value1), (key2, value2)) in zip(Dic1.items(),  Dic2.items()):
 if value1[1:]==value2[1:]:
     value1.append(value2[:1])     
     del Dic1[Value2]

但是我有问题,因为字典很大,我需要一个节省时间的方法,我想到了set但我不知道如何使用它。

1 个答案:

答案 0 :(得分:0)

以下内容应产生所需的结果:

Dic1={0:['F','15','O+','5'],1:['M','12','O+'],2:['F','20','O-'],3:['F','10','A+'],4:['M','45','?']}
Dic2={0:['M','15','O+','5'],1:['M','12','O+'],2:['F','20','A-'],3:['F','10','A+'],4:['F','15','?'],5:['M','10','A+']}

for i in Dic1.keys():
    if Dic1[i][1:] == Dic2[i][1:]:
        if Dic1[i][0] == Dic2[i][0]:
            Dic1[i][0] = '2' + Dic1[i][0]
        else:
            Dic1[i][0] += ',' + Dic2[i][0]
        Dic2.pop(i) 

print Dic1
print Dic2

以上产生:

{0:['F,M','15','O +','5'],1:['2M','12','O +'],2:['F',' 20','O-'],3:['2F','10','A +'],4:['M','45','?']}

{2:['F','20','A-'],4:['F','15','?'],5:['M','10','A + “]}