简体   繁体   English

合并Dict键值

[英]Merge Dict Key Value

I have two files both with key and value. 我有两个具有键和值的文件。 I am trying to merge them with corresponding key and value . 我正在尝试将它们与相应的keyvalue合并。 Keys are present in both the files and value1 in file1 and value2 in file2 . value1在于文件中,又存在于file1 value1file2 value2中。 The files have many columns and key in both files are in col[0] col[1] 文件有很多列,两个文件中的key都在col[0] col[1]

I am trying to get something like this: 我试图得到这样的东西:

key  value1 value2

Code: 码:

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):

Here, f is one of your files. 在这里, f是您的文件之一。

    for key, value in d:  

If you iterate over the file, you get lines (strings). 如果您遍历文件,则会得到 (字符串)。 When you iterate over a line (string), you get characters . 当您在一行(字符串)上进行迭代时,会得到character So, unless all lines in your files are two characters long, for key, value in d will fail. 因此,除非文件中的所有行都长两个字符,否则for key, value in d将失败。

The rest of your code ( cols = row.strip().split() ) seems right, although, it's not clear where row comes from. 您的其余代码( cols = row.strip().split() )似乎正确,但是,尚不清楚row来源。 As Ashwini Chaudhary said, you probably wanted for row in d 正如Ashwini Chaudhary所说,您可能想for row in d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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