如何以正确的格式获得输出

时间:2016-10-10 06:37:00

标签: python

enter image description here

def read_ndfa(file : open) -> {str:{str:{str}}}:
    pass

file =

start;0;start;1;start;0;near
near;1;end
end

正确输出= {'end': {}, 'start': {'1': {'start'}, '0': {'start', 'near'}}, 'near': {'1': {'end'}}}

我需要编写一个函数,它将文件作为输入来获得如上所述的正确输出。但是,我不知道如何使用zip函数创建内部字典。有人能告诉我正确的方法吗?非常感谢。

1 个答案:

答案 0 :(得分:0)

你可以看看这个:

import csv

f = open('data.csv', 'r')

r = csv.reader(f, delimiter=';')

out = {}

for row in r:
    out[row[0]] = {} # Set the top level key

    # Loop on all odd elements
    for pos in range(1, len(row), 2):

        if row[pos] in out[row[0]]:
            # Add the element to the existing set
            out[row[0]][row[pos]].add(row[pos+1])
        else:
            # Create a new set for the key
            out[row[0]][row[pos]] = set([row[pos+1]])

print(out)

f.close()

给出了:

{'near': {'1': {'end'}}, 'end': {}, 'start': {'0': {'near', 'start'}, '1': {'start'}}}
相关问题