繁体   English   中英

合并Dict键值

[英]Merge Dict Key Value

我有两个具有键和值的文件。 我正在尝试将它们与相应的keyvalue合并。 value1在于文件中,又存在于file1 value1file2 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM