[英]Python - Read a complicated file into dictionary
My input file is:我的输入文件是:
-150 150 -90 130 1
-150 150 -150 170 1
-150 150 -110 140 1
-150 160 -80 -20 1
-150 170 -140 160 1
-150 170 -70 -40 1
-140 -170 -110 150 1
-140 130 -120 110 1
-140 140 160 -150 1
-140 160 -150 150 1
I need to create a python dictionary such that the key is the first two columns, and the value is another dictionary where key is 3+4 columns, and value is 5th column:我需要创建一个 python 字典,使得键是前两列,值是另一个字典,其中键是 3+4 列,值是第 5 列:
'-140 160' : {'-150 150' : 0.0188679245283019},
'-140 -170' : {'-110 150' : 0.0188679245283019},
'-150 170' : {'-140 160' : 0.0188679245283019, '-70 -40' : 0.0188679245283019},
'-150 160' : {'-80 -20' : 0.0188679245283019},
'-150 150' : {'-150 170' : 0.0188679245283019, '-110 140' : 0.0188679245283019}
So far I've been using a perl script to convert it to text that looks like what I show above, and then copy paste that text into my python code.到目前为止,我一直在使用 perl 脚本将其转换为类似于我上面显示的文本,然后将该文本复制粘贴到我的 python 代码中。 (the value has become a fraction because I divided it by total sum, which was 56 (这个值变成了分数,因为我将它除以总和,即 56
from collections import defaultdict
bigdict = defaultdict(dict)
for ln in file:
a,b,c,d,e = ln.split()
bigdict[(a,b)][(c,d)] = e
If you want string keys, replace (a,b)
with '%s %s' % (a, b)
and similarly for (c,d)
.如果您想要字符串键,请将(a,b)
替换为'%s %s' % (a, b)
并类似地替换(c,d)
。
This should work:这应该有效:
f = open('file')
dictionary = {}
for line in f:
a, b, c, d, e = line.split()
try:
dictionary['%s %s' % (a, b)]['%s %s' % (c, d)] = e
except KeyError:
dictionary['%s %s' % (a, b)] = dict([('%s %s' % (c, d), e)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.