简体   繁体   English

在python中重新格式化字典输出

[英]Reformatting Dictionary output in python

I have an OrderedDict and I've exported it to a csv but I want it to be formatted differently. 我有一个OrderedDict,并将其导出到csv,但是我希望它采用不同的格式。

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: 我的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? 如何格式化它,使其以这种方式显示在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. 编辑:我看过https://docs.python.org/2.7/howto/sorting.html,itemgetter (),并按python中的值对字典进行排序( 如何按字典值对字典列表进行排序在Python中? ),但我仍然无法让它看起来像我想要的那样。

This will format it the way you described: First it writes a header row using the first entry in the list to figure out the names for the columns and then it writes the rest of the rows. 这将按照您描述的方式进行格式化:首先,它使用列表中的第一个条目写入标题行,以找出列的名称,然后写入其余的行。

writer = csv.writer(open('sortedcounts.csv', 'wb'))
header = ['Top Calling Customers'] + list(list(sorted_counts.values())[0].keys())
writer.writerow(header)
for key, value in sorted_counts.items():
    writer.writerow([key] + list(value.values()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM