python - Importing/Exporting a nested dictionary from a CSV file -


so have csv file data arranged this:

x,a,1,b,2,c,3 y,a,1,b,2,c,3,d,4 z,l,2,m,3 

i want import csv create nested dictionary looks this.

data = {'x' : {'a' : 1, 'b' : 2, 'c' : 3},          'y' : {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4},         'z' : {'l' : 2, 'm' :3}} 

after updating dictionary in program wrote (i got part figured out), want able export dictionary onto same csv file, overwriting/updating it. want in same format previous csv file can import again.

i have been playing around import , have far

import csv data = {} open('userdata.csv', 'r') f:         reader = csv.reader(f)     row in reader:        data[row[0]] = {row[i] in range(1, len(row))} 

but doesn't work things not arranged correctly. numbers subkeys other numbers, letters out of place, etc. haven't gotten export part yet. ideas?

since you're not interested in preserving order, relatively simple should work:

import csv  # import data = {} open('userdata.csv', 'r') f:     reader = csv.reader(f)     row in reader:         = iter(row[1:])         data[row[0]] = dict(zip(a, a))  # export open('userdata_exported.csv', 'w') f:     writer = csv.writer(f)     key, values in data.items():         row = [key] + [value item in values.items() value in item]         writer.writerow(row) 

the latter done little more efficiently making single call thecsv.writer's writerows()method , passing generator expression.

# export2 open('userdata_exported.csv', 'w') f:     writer = csv.writer(f)     rows = ([key] + [value item in values.items() value in item]             key, values in data.items())     writer.writerows(rows) 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -