Python 比较两个字典,查找共同值
我还是个初学者,需要帮忙解决我的代码问题。
我有两个文件,里面的内容是列表格式,我想把它们当作字典来用。这两个文件的格式是一样的。第一列是键,第二列是对应的值,用“|”分隔。并不是所有的键在两个文件中都有。
举个例子: File1.txt
1 b|c
2 a|b|d
3 a|b|c
4 a|b
9 a|b|c
File2.txt
1 a|c
2 a|b|c|d|e
3 a|b|c
6 a|b|c
7 a|b|c
8 a|b|c
9 x|y
我想创建一个文件 File3.txt,里面包含每个键的共同值,并且每个键都要显示。如果某个键在两个列表中没有共同值,就留空;如果某个键在两个列表中有,但没有共同值,就写“没有匹配”。(最后那部分是我临时想到的,所以在我下面的代码里没有体现。)
例如: File3.txt
1 c
2 a|b|d
3 a|b|c
4
6
7
8
9 no matches
以下是我到目前为止写的代码。我觉得我可能完全偏离了方向,但希望能得到一些帮助。谢谢!
#!/usr/bin/env python
table = {}
ref2gene = {}
table2 = {}
ref2gene2 = {}
with open('File1.txt') as f_in:
for line in f_in:
row = line.strip()
table[line.split('\t')[0]] = line.split('\t')[1]
gene_name = row[0]
for ref in row[1].split('|'):
ref2gene[ref] = gene_name
with open('File2.txt') as f_1, open('File3.txt', 'w') as f_2:
for line in f_1:
row2 = line.strip()
table2[line.split('\t')[0]] = line.split('\t')[1]
gene_name2 = row2[0]
for ref2 in row2[1].split('|'):
ref2gene2[ref2] = gene_name2
def intersect_two_dicts (table, table2):
return { k:v for k,v in table.iteritems() if ((k in table2)and(table[k]==table2[k])) }
print (intersect_two_dicts(dicts[0], dicts[1]))
1 个回答
0
试试这个方法,使用字典我们可以解决这个问题,只需把 print
替换成文件的 write
。
file1=open('a.txt','r')
file1=file1.readlines()
file1={i.split()[0]:i.split()[1] for i in file1}
print file1
#{'1': 'a|c', '3': 'a|b|c', '2': 'a|b|c|d|e', '7': 'a|b|c', '6': 'a|b|c', '9': 'x|y', '8': 'a|b|c'}
file2=open('b.txt','r')
file2=file2.readlines()
file2={i.split()[0]:i.split()[1] for i in file2}
print file2
#{'1': 'b|c', '9': 'a|b|c', '3': 'a|b|c', '2': 'a|b|d', '4': 'a|b'}
keys=set(file1.keys()+file2.keys())
for i in sorted(keys):
if i in file1 and i in file2:
file1_values=file1[i].split('|')
file2_values=file2[i].split('|')
intersec=set(file1_values)&set(file2_values)
if len(intersec)>0:
print i,'|'.join(intersec)
else:print i, 'missing values'
else:
print i,'empty'
总输出
1 c
2 a|b|d
3 a|c|b
4 empty
6 empty
7 empty
8 empty
9 missing values