2015-06-05 256 views
1

我有一個OrderedDict,我已經將它導出到csv,但我希望它的格式不同。python重新格式化字典輸出

我閱讀代碼,整理,使詞典:

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?)中的值排序字典,但我仍然無法使它看起來如何我想要的。

+1

看看http://stackoverflow.com/questions/8331469/python-dictionary-to-csv – kponz

+0

@kponz說實話,我沒有發現他是特別有幫助的/她試圖讓字典回到一個CSV ...我沒有問題。這是我無法解決的格式。 – jenryb

回答

1

這將按照您描述的方式進行格式化:首先使用列表中的第一個條目寫入標題行,以找出列的名稱,然後寫入其餘行。

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