Sorting a dictionary and writing it to a CSV file

I have a dictionary with a tuple as a key and a list as values

myDict = { (1, 9078752378): [('Smith', 'Bob'), 'Head guard'], (2, 9097615707): [('Burdell', 'George'), 'Lifeguard'], (3, 9048501430): [('Smith', 'Amanda'), 'Lifeguard'], (4, 9026450912): [('Brown', 'John'), 'Lifeguard'], (5, 9027603006): [('Flowers', 'Claudia'), 'Lifeguard'], (6, 9055520890): [('Smith', 'Brown'), 'Head guard'], (7, 9008197785): [('Rice', 'Sarah'), 'Lifeguard'], (8, 9063479070): [('Dodd', 'Alex'), 'New Lifeguard'], (9, 9072301498): [('Sparrow', 'Jack'), 'New Lifeguard'], (10, 9084389677): [('Windsor', 'Harry'), 'New Lifeguard'] } 

I am completely obsessed with how to write this dictionary to a csv file so that those written in this format

 1 9078752378 Smith Bob Head guard 

.. and so on until 9

PLEASE, HELP!!!

+3
source share
2 answers

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

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

I have to warn you about a potential gotcha in your output format, although if you need to parse this again, you want to specify values ​​or use a different delimiter, for example:

1 9078752378 Smith Bob "Head guard"

+4
source
 with open("CSV", 'w') as f: f.write('\n'.join([",".join(map(str,[a,b,c,d,e])) for (a, b), ((c, d), e) in sorted(myDict.items())])) 

Explanation -

sorted(myDict.items()) will sort 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])) joins the unpacked values ​​with a comma.

[",".join(map(str,[a,b,c,d,e])) for (a, b), ((c, d), e) in sorted(myDict.items())] - This is an understanding of the list of the above values, separated by commas.

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

+3
source

All Articles