我想从一个包含两个键和14个值的文本文件中创建一个字典:
data.txt:
Key1 Key2 Val1 Val2 Val3…Val14
100 a x0 y0 z0………n0
101 a x1 y1 z1………n1
102 b x2 y2 z2………n2
103 b x3 y3 z3………n3
104 c x4 y4 z4………n4
105 c x5 y5 z5………n5
…
140 m xm ym zm………nm
字典应该是这样的:
{100: {a: [x0, y0, z0,…n0]},
101: {a: [x1, y1, z1,…n1]},
102: {b: [x2, y2, z2,…n2]},
103: {b: [x3, y3, z3,…n3]},
…
140: {m: [xm, ym, zm,…nm]}}
我试过Code1和Code2。Code1提供了一个非常大的字典,其中的行是重复的,并附加其他行。Code2给出错误TypeError:不可处理的类型:"slice"。
Code1:
lookupfile = open("data.txt", 'r')
lines = lookupfile.readlines()
lookup = lines[1:] # Start the dictionary from row 1, exclude the column names
d={}
for line in lookup:
dic = line.split()
d.update({dic[0]: {dic[1]: dic[2:]}})
print(d)
Code2:
data = defaultdict(dict)
with open('data.txt', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
data[row['Key1']][row['Key2']]=row['Val1':]
print (data)
我希望代码看起来像Code2,这样我以后就可以使用列名了。但是,如果有任何帮助,我将不胜感激。
如果需要,我可以提供更多信息。
s="""Key1 Key2 Val1 Val2 Val3…Val14
100 a x0 y0 z0
101 a x1 y1 z1
102 b x2 y2 z2
103 b x3 y3 z3
104 c x4 y4 z4
105 c x5 y5 z5"""
d = {}
for line in s.splitlines()[1:]:
spl = line.split()
d[spl[0]] ={spl[1]:spl[2:]}
from pprint import pprint
pprint(d)
{'100': {'a': ['x0', 'y0', 'z0']},
'101': {'a': ['x1', 'y1', 'z1']},
'102': {'b': ['x2', 'y2', 'z2']},
'103': {'b': ['x3', 'y3', 'z3']},
'104': {'c': ['x4', 'y4', 'z4']},
'105': {'c': ['x5', 'y5', 'z5']}}
同样的逻辑也适用于文件代码,跳过对文件对象的第一行调用next
。然后简单地按照上面的方式对每一行进行索引。
d = {}
with open('data.txt', 'r') as f:
next(f) # skip header
for row in f:
spl = line.split()
# slicing using spl[2:] will give you a list of all remaining values
d[spl[0]] = {spl[1]:spl[2:]}
如果列之间确实有多个空格,那么使用str.split
将比使用csv模块效果更好。
您使用的是DictReader
,因此每个row
都是dict
,并且您不能对dict
进行切片(正如您试图在赋值的RHS上所做的那样)。
因此,使用一个普通的csv.reader
(因此每个row
都是一个list
,可以切片)和:
data[row[0]][row[1]]=row[2:]