[英]Merge Dict Key Value
我有兩個具有鍵和值的文件。 我正在嘗試將它們與相應的key
和value
合並。 鍵value1
在於文件中,又存在於file1
value1
和file2
value2
中。 文件有很多列,兩個文件中的key
都在col[0] col[1]
我試圖得到這樣的東西:
key value1 value2
碼:
from collections import defaultdict
d2 = {}
with open('file2.txt', 'r') as file2:
for row in file2:
cols = row.strip().split()
#print(cols);
key = cols[0], cols[1]
value1 = cols[4]
with open('file1.txt', 'r') as file1:
for row in file1:
cols = row.strip().split()
#print(cols);
key = cols[0], cols[1]
value2 = cols[2]
print ("%s %s %s %s\n" % (d2[cols[0]], d2[cols[1]], d2[cols[4]], d2[cols[2]]))
Error:
Traceback (most recent call last):
File "test_two.py", line 21, in <module>
print ("%s %s %s %s\n" % (d2[cols[0]], d2[cols[1]], d2[cols[4]], d2[cols[2]]))
KeyError: '3545' (first line)
for d in (file1,file2):
在這里, f
是您的文件之一。
for key, value in d:
如果您遍歷文件,則會得到行 (字符串)。 當您在一行(字符串)上進行迭代時,會得到character 。 因此,除非文件中的所有行都長兩個字符,否則for key, value in d
將失敗。
您的其余代碼( cols = row.strip().split()
)似乎正確,但是,尚不清楚row
來源。 正如Ashwini Chaudhary所說,您可能想for row in d
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.