Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中重新格式化字典输出_Python_Csv_Formatting_Ordereddictionary - Fatal编程技术网

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

在python中重新格式化字典输出,python,csv,formatting,ordereddictionary,Python,Csv,Formatting,Ordereddictionary,我有一个OrderedDict,我已经将其导出到csv,但我希望它的格式不同 我用于阅读、排序和制作词典的代码: 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

我有一个OrderedDict,我已经将其导出到csv,但我希望它的格式不同

我用于阅读、排序和制作词典的代码:

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])
我的输出:

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})])
我的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}
我希望它看起来像这样:

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,
如何格式化它,使其以这种方式显示在我的csv中


编辑:我已经在python()中查看了、itemgetter()和按值对字典进行排序,但我仍然无法让它看起来像我希望的那样。

这将按照您描述的方式对其进行格式化:首先,它使用列表中的第一个条目写入标题行,以找出列的名称,然后它写入其余行

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()))

请看一下@kponz,老实说,我没有发现它特别有用,因为他/她正试图将字典恢复到CSV。。。我对此没有问题。这是我无法解决的格式问题。