Skip to content Skip to sidebar Skip to footer

Sorting A Dictionary And Writing It To A Csv File

I have a dictionary with a tuple as a key and list as values myDict = { (1, 9078752378): [('Smith', 'Bob'), 'Head guard'], (2, 9097615707): [('Burdell', 'George'), 'Lifeguard'],

Solution 1:

Assuming your format is consistent, this should do the trick:

withopen('youfile.csv', 'w') as f:
  for k,v insorted(myDict.iteritems()):
    f.write('{} {} {} {} {}\n'.format(k[0], k[1], v[0][0], v[0][1], v[1]))

I should warn you about a potential gotcha in your output format though, if you need to parse this back again you want to quote values, or use a different separator, e.g.:

1 9078752378 Smith Bob "Head guard"

Solution 2:

withopen("CSV", 'w') as f:
   f.write('\n'.join([",".join(map(str,[a,b,c,d,e])) for (a, b), ((c, d), e) insorted(myDict.items())]))

Explanation -

sorted(myDict.items()) will sort the the dictionary based on keys.

for (a, b), ((c, d), e) in sorted(myDict.items()) will unpack your values.

",".join(map(str,[a,b,c,d,e])) will join the unpacked values by comma.

[",".join(map(str,[a,b,c,d,e])) for (a, b), ((c, d), e) in sorted(myDict.items())] is the list comprehension of the above comma-joined values.

'\n'.join([",".join(map(str,[a,b,c,d,e])) for (a, b), ((c, d), e) in sorted(myDict.items())] will join the above list with newlines.

Post a Comment for "Sorting A Dictionary And Writing It To A Csv File"