创建未知深度的嵌套字典并将最内层的键初始化为列表?

时间:2018-06-08 13:32:59

标签: python list dictionary initialization

我想创建一个深度未知的字典,并将最里面的键初始化为列表而不是字典。

Code I' m now now(有效):

nested_dict = lambda: defaultdict(nested_dict)
inputdict = nested_dict()

with open('inputdata.txt','r') as inputfile:
    inputobject = csv.DictReader(inputfile,delimiter=' ',skipinitialspace=True)
    for row in inputobject:

        try: inputdict[row['platform']][row['sensor']]['time'].append(float(row['time']))
        except AttributeError: inputdict[row['platform']][row['sensor']]['time'] = [float(row['time'])]

        try: inputdict[row['platform']][row['sensor']]['w'].append(float(row['w']))
        except AttributeError: inputdict[row['platform']][row['sensor']]['w'] = [float(row['w'])]
        ...

我想简单地添加或初始化inputdict[row['platform']][row['sensor']]['time']等,而无需尝试/除了我要保存的每一列。这可能吗?我真的只想写一行而不是两行,所以代码看起来更好......

输入数据格式:

time ms platform sensor P/S w x y z nl ns conf flag1 flag2
581083200 29000 C 1 P -0.16900 0.22519 0.77034 -0.57209 0 52 2 11000001 11000000
581083200 29000 C 2 P 0.87761 -0.13123 -0.44549 0.11875 0 32 1 11000001 11000000
581083200 29000 C 3 P 0.66907 0.13427 0.46785 -0.56162 0 88 2 11000001 11000000
581083200 529000 C 1 P -0.16911 0.22505 0.77021 -0.57229 0 50 2 11000001 11000000
...

0 个答案:

没有答案