Python-来自文件的具有两个键和多个值的字典

Python-Dictionary from file with two keys and multiple values

(这个问题已经在之前关于 Whosebug 的几篇文章中得到了回答。但是,我无法得到正确的结果,我不知道我做错了什么?)

我想从包含两个键和 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。代码 1 给出了一个非常大的字典,其中重复行并附加了其他行。 Code2 给出错误 TypeError: unhashable type: '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:]