我有以下defaultdictionary。我试图将字典的值写入文件。但它是在一行写作。我想在每个项目后添加新的行字符。帮忙?
defaultdict(<type 'list'>, {'11163722404385': [('#3\n', '2089', '', '', '', 'Con verted', '', '', '', 'Mon Apr 22 13:32:00 PDT 2013', 'UNATT')], '1116372240485':
[('#3\n', '2089', '', '', '', 'Converted', '', '', '', 'Mon Apr 22 13:31:00 PDT
2013', 'UNATT'), ('#3\n', '2089', '', '', '', 'Converted', '', '', '', 'Mon Apr
22 13:31:14 PDT 2013', 'UNATT'), ('#3\n', '2089', '', '', '', 'Converted', '',
'', '', 'Mon Apr 22 13:32:00 PDT 2013', 'UNATT')]})
accounts = defaultdict(list)
with open('C:\fileReport.txt', 'a') as csvoutput:
writer = csv.writer(csvoutput)
for sid,data1 in accounts.iteritems():
report = [';'.join(items) for items in data1]
print report
finalReport = ['{},{}'.format(sid, ''.join(report))]
writer.writerow(report)
writer.writerow('\n')
答案 0 :(得分:1)
这有点乱,你没有指定你期望的输出。这就是我认为你想要做的事情:
<强>代码:强>
from collections import defaultdict
accounts = defaultdict(list)
accounts['11163722404385'] = [('a', 'list'),('another', 'list')]
accounts['1116372240485'] = [('one', 'more')]
with open(r'C:\temp\out.txt', 'a') as writer:
for k,v in accounts.iteritems():
csv = ';'.join([','.join(t) for t in v])
writer.write("%s,%s\n" % (k, csv))
<强>输出:强>
11163722404385,a,list;another,list
1116372240485,one,more
您可能需要重新考虑数据结构。
答案 1 :(得分:1)
听起来像是pprint
:
>>> from pprint import pprint
>>> pprint(accounts)
{'11163722404385': [('#3\n',
'2089',
'',
'',
'',
'Converted',
'',
'',
'',
'Mon Apr 22 13:32:00 PDT 2013',
'UNATT')],
'1116372240485': [('#3\n',
'2089',
'',
'',
<etc.> ]}