打印有序字典的漂亮格式使用pprin

2024-06-02 06:05:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pprint来很好地打印dict,而且工作正常。现在我切换到使用来自模块collectionsOrderedDict。不幸的是,pprint路由似乎没有意识到这样的对象或多或少也是dicts,并返回到以长行打印的方式。在

>>> d = { i:'*'*i for i in range(8) }
>>> pprint.pprint(d)
{0: '',
 1: '*',
 2: '**',
 3: '***',
 4: '****',
 5: '*****',
 6: '******',
 7: '*******'}
>>> pprint.pprint(collections.OrderedDict(d))
OrderedDict([(0, ''), (1, '*'), (2, '**'), (3, '***'), (4, '****'), (5, '*****'), (6, '******'), (7, '*******')])

还有什么方法可以更好地表示OrderedDicts吗?也许即使它们被嵌套在一个正常的dict或{}内的?在


Tags: 模块对象方法in路由for方式range
3条回答

如果您专门针对CPython*3.6或更高版本,那么您可以just use regular dictionaries而不是{}。您将错过一些methods exclusive to ^{},这还不能保证可移植到其他Python实现,**但这可能是完成您正在尝试的最简单的方法。在

*CPython是Python的参考实现,可以从python.org网站.
**CPythonstole this idea from PyPy,因此您可能也可以依赖它在那里工作。在

我找到了一个相对简单的解决方案,但是它包含了使有序字典的输出看起来完全像一个常规的dict对象的风险。在

使用上下文管理器防止pprint排序字典键的原始解决方案来自this answer。在

@contextlib.contextmanager
def pprint_OrderedDict():
    pp_orig = pprint._sorted
    od_orig = OrderedDict.__repr__
    try:
        pprint._sorted = lambda x:x
        OrderedDict.__repr__ = dict.__repr__
        yield
    finally:
        pprint._sorted = pp_orig
        OrderedDict.__repr__ = od_orig

(您也可以用dict.__repr__来修补OrderedDict.__repr__方法,但请不要这样做。)

示例:

^{pr2}$

试试这个:

d = collections.OrderedDict({ i:'*'*i for i in range(8) })

编辑

pprint.pprint(list(d.items()))

相关问题 更多 >