BAI
BAI

Reputation: 621

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'],
 (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 stuck on how to write this dictionary to a csv file in order written in this format

1 9078752378 Smith Bob Head guard

..and so on to 9

PLEASE HELP!!!

Upvotes: 3

Views: 3309

Answers (2)

Rahul
Rahul

Reputation: 1505

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 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.

Upvotes: 3

wim
wim

Reputation: 363163

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 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"

Upvotes: 4

Related Questions