Reputation: 125
I am trying to sort a dictionary by key as well as value to create an output CSV file, I am having trouble getting the desired output file.
I've tried sorting the keys separately and the list of values separately but when outputting to the file the pairs are messed up.
data = {}
with open(filename, mode = 'r') as f:
reader = csv.reader(f, delimiter = ',')
for n, row in enumerate(reader):
if not n:
continue
category, value = row
if category not in data:
data[category] = set()
data[category].add((value))
columnNames = sorted(data.keys())
columnValues = []
for value in data.values():
columnValues.append(sorted(value))
print(columnValues)
with open('sorteddata.csv', 'w') as outfile:
writer = csv.writer(outfile, delimiter = ',')
writer.writerow(columnNames)
writer.writerows(zip_longest(*columnValues))
If the input is {'number': {54, 1, 95, 78, 85, 87}}, 'name': {'bob', 'steve', 'alex'}, 'color': {'blue', 'yellow', 'black'}} the output should be {'color': {'black', 'blue', 'yellow'}, 'name': {'alex', 'bob', 'steve'}, 'number': {1, 54, 78, 85, 87, 94}}
Instead I get an output that looks like {'color': {'alex', 'bob', 'steve'}, 'name': {'black', 'blue', 'yellow'}, 'number': {1, 54, 78, 85, 87, 94}} where the color and name values are swapped but in the correct order.
Upvotes: 1
Views: 41
Reputation: 929
here you are sorting the keys and values independently, and not linking them correctly. You need to sort with the keys first and then for the corresponding values, sort the list
Here is a working solution with OrderDict
import collections
inp = {
'number': {54, 1, 95, 78, 85, 87},
'name': {'bob', 'steve', 'alex'},
'color': {'blue', 'yellow', 'black'}}
ans = collections.OrderedDict()
for item in sorted(inp): # sorting with the key
val = sorted(inp[item]) # fetching the value list from the input dict
print(item, val)
ans[item] = sorted(val) # saving the item and sorted values, in the new list
print(ans)
Upvotes: 1