使用断行格式化python词典

时间:2017-07-18 15:29:47

标签: python dictionary line break

我有这本词典;

results = {'name': sectionAddr.name,
               'count': sampleCount,
               'finish_count': len(finished),
               'inside4_count': inside4Count,
               'inside10_count': inside10Count,
               'finish_rate': 100 * len(finished) / sampleCount,
               'inside4_rate': 100 * inside4Count / sampleCount,
               'inside10_rate': 100 * inside10Count / sampleCount,
               'mean_error': meanError,
               'stddev_error': stddevError,
               'samples': sampleResults}
    results['error'] = getError(results

但我需要展示它;如果我通过格式化为str来做,它看起来像一个字符串,即一条线。我应该如何在每个变量后断线?

类似的东西:

results = {'name': sectionAddr.name + '\n', 
'finish_count': len(finished), ...

不起作用,

我怎么能破线?

3 个答案:

答案 0 :(得分:1)

漂亮的印刷品可能会满足您的需求;

import pprint
pprint.pprint(result)

如果您不想使用漂亮的印刷品;

result = {'a': '1',
          'b': '2',
          'c': '3'}

print('\n'.join('\t'.join((key, result[key])) for key in result))

输出;

a   1
c   3
b   2

答案 1 :(得分:1)

您可以使用pprint.pformat来获取格式正确的字符串:

import pprint

results = {'name': "sectionAddr.name",
               'count': "sampleCount",
               'finish_count': "len(finished)",
               'inside4_count': "inside4Count",
               'inside10_count': "inside10Count",
               'samples': "sampleResults"}

s = pprint.pformat(results)

print(s)

输出:

{'count': 'sampleCount',
 'finish_count': 'len(finished)',
 'inside10_count': 'inside10Count',
 'inside4_count': 'inside4Count',
 'name': 'sectionAddr.name',
 'samples': 'sampleResults'}

或者,如果您不需要它作为字符串但想直接打印到控制台,则可以使用pprint.pprint

pprint.pprint(results)

请注意,字典没有固定顺序,因此格式化字符串中的键可能顺序不同。

pformatpprint都接受其他参数,因此您可以修改结果:docs

答案 2 :(得分:0)

Python Pretty Printer Documentation

>>> import pprint
>>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
... ('parrot', ('fresh fruit',))))))))
>>> stuff = ['a' * 10, tup, ['a' * 30, 'b' * 30], ['c' * 20, 'd' * 20]]
>>> pprint.pprint(stuff)
['aaaaaaaaaa',
 ('spam',
  ('eggs',
   ('lumberjack',
    ('knights', ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
 ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
 ['cccccccccccccccccccc', 'dddddddddddddddddddd']]

您的用例:

import pprint
pprint.pprint(results)