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

标签 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, 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 中以这种方式显示?

编辑:我看过https://docs.python.org/2.7/howto/sorting.html 、 itemgetter() 以及按 python 中的值对字典进行排序 ( How do I sort a list of dictionaries by values of the dictionary in Python? ),但我仍然无法使其看起来像我想要的那样。

最佳答案

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

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

关于python - 在 python 中重新格式化字典输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30674101/

相关文章:

python - 将 curl 调用转换为 python 请求

python - 多个线程从 Linux 上的单个文件夹读取

html - 粘贴似乎在 html 代码中被禁用(但实际上并没有禁用它)

asp.net-mvc - 具有自定义格式的 ASP.NET MVC ViewModel 映射

python - 为什么在 python 请求中使用 iter_content 和 chunk_size

python - 在正则表达式中匹配同一字符类的两个不同重复是更好的方法吗?

java - CSV - java.util.scanner 跳过一个值并选择下一个值

javascript - 从 .csv 中提取的变量不会添加

python - Pyspark 按列分组元素并创建字典

Java 用 printf 格式化宽度; '$' 不随数字移动