0

我有以下默认字典。我正在尝试将字典的值写入文件。但它写在一行中。我想在每个项目后添加换行符。帮助 ?

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')
4

2 回答 2

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

您可能需要重新考虑您的数据结构。

于 2013-05-22T07:09:12.070 回答
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.> ]}
于 2013-05-22T07:14:01.410 回答