将列表转换为嵌套的dic并分配值

时间:2015-07-13 18:57:15

标签: python dictionary

我正在尝试将csv转换为Json。如果我遇到带有命名约定"columnName1.0.columnName2.0.columnName3"的csv头文件,我需要创建一个嵌套的JSON - > {ColumnName1 : {columnName2 : {columnName3 : value }}} ..

到目前为止,我能够将标题拆分为subColumnNames列表并创建嵌套的JSON类型,但我无法分配值。任何帮助?

    data = open(str(fileName.strip("'")),'rb')
    reader = csv.DictReader(data,delimiter = ',',quotechar='"')

    ''' 
        Get the header '''

    for line in reader:
        for x,y in line.items():
            columns = re.split("\.\d\.",x)
            if len(columns) == 1:
                continue
            else:
                print "COLUMNS %s"%columns
                testLine = {}
                for subColumnName in reversed(columns):
                    testLine = {subColumnName: testLine}
                ''' Need to Assign value y? '''    
                print "LINE%s"%testLine

输出:

COLUMNS ['experience', 'title']
LINE{'experience': {'title': {}}}
COLUMNS ['experience', 'organization', 'profile_url']
LINE{'experience': {'organization': {'profile_url': {}}}}
COLUMNS ['experience', 'start']
LINE{'experience': {'start': {}}}
COLUMNS ['raw_experience', 'organization', 'profile_url']
LINE{'raw_experience': {'organization': {'profile_url': {}}}}
COLUMNS ['raw_experience', 'end']
LINE{'raw_experience': {'end': {}}}
COLUMNS ['experience', 'organization', 'name']
LINE{'experience': {'organization': {'name': {}}}}

1 个答案:

答案 0 :(得分:0)

您想要的值目前为{},即testLine的初始值。你可以试试这个:

testLine = value
for subColumnName in reversed(columns):
    testLine = {subColumnName: testLine}