這裏是我的原代碼:關於我在比較兩本字典時遇到的問題的建議?
import csv
with open ("filename1.txt") as f:
dict1 = {}
r = csv.reader(f,delimiter="\t")
for row in r:
a, b, v = row
dict1.setdefault((a,b),[]).append(v)
for key in dict1:
print(key[0])
print(key[1])
print(d[key][0]])
我想這永遠柱當然打印此代碼。例如,這裏是它打印的文本文件的一個例子。我有過我的鑰匙控制,我可以打印第1列,2或3
7 10165876 0.457295035
6 145989671 0.738336666
3 225038504 0.575564389
然而,當我實現這個代碼,並試圖比較兩本字典,我再也不用在我的鑰匙控制和我得到錯誤:
import csv
with open ("filename1.txt") as f:
dict1 = {}
r = csv.reader(f,delimiter="\t")
for row in r:
a, b, v = row
dict1.setdefault((a,b),[]).append(v)
#for key in dict1:
#print(key[0])
#print(key[1])
#print(d[key][0]])
with open ("filename2.txt") as f:
dict2 = {}
r = csv.reader(f,delimiter="\t")
for row in r:
a, b, v = row
dict2.setdefault((a,b),[]).append(v)
#for key in dict2:
#print(key[0])
count = 0
for key in dict1:
for key in dict2:
if (dict1[0] == dict2[0]) and abs(dict1[1] - dict2[1]) < 10000:
count +=1
錯誤:
Traceback (most recent call last):
File "/Users/macbookpro/Desktop/MainDict.py", line 29, in <module>
if (dict1[0] == dict2[0]) and abs(dict1[1] - dict2[1]) < 10000:
KeyError: 0
我GOOGLE了,我明白什麼錯誤意味着,但它有什麼用我的代碼呢?正如我之前提到的,在原始代碼中,我沒有得到KeyError。但現在當我把所有東西放在一起時,
爲什麼我得到一個KeyError,我該如何改變我的代碼並修復它?
你在哪裏添加了鍵'0'? –