Python 将字典保存到文件
我有一个这样的文件:Python 将字典保存到文件,python,Python,我有一个这样的文件: 732772 scaffold-3 G G A 732772 scaffold-2 G G A 742825 scaffold-3 A A G 776546 scaffold-3 G A G 776546 scaffold-6 G A G res = open('00test','r') out = open('00testresult','w') d = {} for line in res: if
732772 scaffold-3 G G A
732772 scaffold-2 G G A
742825 scaffold-3 A A G
776546 scaffold-3 G A G
776546 scaffold-6 G A G
res = open('00test','r')
out = open('00testresult','w')
d = {}
for line in res:
if not line.startswith('#'):
line = line.strip().split()
pos = line[0]
name = line[1]
call = line[2]
father = line[3]
mother = line[4]
if not (name in d):
d[name] = []
d[name].append({'pos':pos,'call':call,'father':father,'mother':mother})
我感兴趣的是使用第2列作为键,并以这样的方式输出:拥有唯一的键,并与它的值关联
换句话说,如果第2列中的名称出现多次,则只输出一次,因此输出应为:
scaffold-3
732772 G G A
742825 A A G
776546 G A G
scaffold-2
732772 G G A
scaffold-6
776546 G A G
我写了这样的东西:
732772 scaffold-3 G G A
732772 scaffold-2 G G A
742825 scaffold-3 A A G
776546 scaffold-3 G A G
776546 scaffold-6 G A G
res = open('00test','r')
out = open('00testresult','w')
d = {}
for line in res:
if not line.startswith('#'):
line = line.strip().split()
pos = line[0]
name = line[1]
call = line[2]
father = line[3]
mother = line[4]
if not (name in d):
d[name] = []
d[name].append({'pos':pos,'call':call,'father':father,'mother':mother})
但我不知道如何以我上面描述的方式输出它
任何帮助都很好
编辑:
这是完全可以工作的代码,解决了问题:
res = open('00test','r')
out = open('00testresult','w')
d = {}
for line in res:
if not line.startswith('#'):
line = line.strip().split()
pos = line[0]
name = line[1]
call = line[2]
father = line[3]
mother = line[4]
if not (name in d):
d[name] = []
d[name].append({'pos':pos,'call':call,'father':father,'mother':mother})
for k,v in d.items():
out.write(str(k)+'\n')
for i in v:
out.write(str(i['pos'])+'\t'+str(i['call'])+'\t'+str(i['father'])+'\t'+str(i['mother'])+'\n')
out.close()
现在您已经有了字典,请在项目上循环并写入文件:
keys = ('pos', 'call', 'father', 'mother')
with open(outputfilename, 'w') as output:
for name in d:
output.write(name + '\n')
for entry in d['name']:
output.write(' '.join([entry[k] for k in keys]) + '\n')
对于d
,您可能希望使用对象而不是常规字典:
from collections import defaultdict
d = defaultdict(list)
如果没有,请删除
(d中的名称):d[name]=[]
行。很抱歉,这没有任何帮助。我可以用我想要的方式打印它,但当它像我声明的那样保存到文件时,它就是不起作用。@Irek:不清楚输出是否必须保存到文件中。更新了。好的,我把最后一部分拿来用了。谢谢,这个解决方案有效。我将用工作代码编辑我的帖子