I have an OrderedDict and I've exported it to a csv but I want it to be formatted differently.
My code for reading, sorting, and making the dictionary:
from collections import defaultdict, OrderedDict
counts = defaultdict(lambda: {"User": 0, "Equipment": 0, "Neither": 0})
with open('sorterexample.csv', 'rb') as fh:
reader = csv.reader(fh, delimiter=',')
headerline = reader.next()
for row in reader:
company, calltype = row[0], row[2]
counts[company][calltype] += 1
sorted_counts = OrderedDict(sorted(counts.iteritems(), key=lambda counts_tup: sum(counts_tup[1].values()), reverse=True))
print(sorted_counts)
writer = csv.writer(open('sortedcounts.csv', 'wb'))
for key, value in sorted_counts.items():
writer.writerow([key, value])
My ouput:
OrderedDict([('Customer1', {'Equipment': 0, 'Neither': 1, 'User': 4}), ('Customer3', {'Equipment': 1, 'Neither': 1, 'User': 2}), ('Customer2', {'Equipment': 0, 'Neither': 0, 'User': 1}), ('Customer4', {'Equipment': 1, 'Neither': 0, 'User': 0})])
My CSV:
Customer1, {'Equipment': 0, 'Neither': 1, 'User': 4}
Customer3, {'Equipment': 1, 'Neither': 1, 'User': 2}
Customer2, {'Equipment': 0, 'Neither': 0, 'User': 1}
Customer4, {'Equipment': 1, 'Neither': 0, 'User': 0}
I want it to look like this:
Top Calling Customers, Equipment, User, Neither,
Customer 1, 0, 4, 1,
Customer 3, 1, 2, 1,
Customer 2, 0, 1, 0,
Customer 4, 1, 0, 0,
How can I format it so it shows up this way in my csv?
edit: I've looked at https://docs.python.org/2.7/howto/sorting.html, itemgetter(), and sorting dictionaries by values in python (How do I sort a list of dictionaries by values of the dictionary in Python?) but I still can't make it look how I want it to.