May-28-2020, 10:11 AM
Hi ,
I come from a perl background and used nested hash tables quite effectively and am unable to achieve the same using the python dictionary. Is it possible or not do something like this in python?
Reading a comma separated file into a deeply nested dictionary and printing it back out
I come from a perl background and used nested hash tables quite effectively and am unable to achieve the same using the python dictionary. Is it possible or not do something like this in python?
Reading a comma separated file into a deeply nested dictionary and printing it back out
inputfile = open('inputdata.csv','r') # see bottom for the data file count = 0 thisdict={} #thisdict = {11:{12:{13:{14:{15:1}}}}} for line in inputfile: line = line.rstrip("\n") items = line.split(",") if count != 0: thisdict[items[0]][items[1]][items[2]][items[3]][items[4]] = 1 ###this throws an error assignment is not acceptable pass count += 1 inputfile.close() ### the code below works if I am able to initialize the deeply nested dictionary using thisdict = {11:{12:{13:{14:{15:1}}}}} print("number of lines read:", count) outfile = open('output2.txt','w') for col1 in thisdict: print(col1) for col2 in thisdict[col1]: print(col2) for col3 in thisdict[col1][col2]: print(col3) for col4 in thisdict[col1][col2][col3]: print(col4) for col5 in thisdict[col1][col2][col3][col4]: print(col5) printline = str(col1) + "," + str(col2) + "," + str(col3) + "," + str(col4) + "," + str(col5) + "," + str(thisdict[col1][col2][col3][col4][col5]) + "\n" outfile.write(printline) outfile.close()#####inputdata.csv#####
Output:col1,col2,col3,col4,col5
11,12,13,14,15
21,22,23,24,25
31,32,33,34,35
41,42,43,44,45
51,52,53,54,55
61,62,63,64,65
71,72,73,74,75
81,82,83,84,85
####end of inputdata.csv#######