【问题标题】:How to pretty print more than one dictionary entry per line?如何每行漂亮地打印多个字典条目?
【发布时间】:2021-07-30 03:13:59
【问题描述】:

我有一本包含许多条目的字典:

d = dict([(i, 'Data') for i in range(100)])

如果我尝试漂亮地打印这些数据

pp = PrettyPrinter(indent=4, width=999)
pp.pprint(d)

每行只打印一个条目:

{   0: 'Data',
    1: 'Data',
    ...
    99: 'Data'}

但是,我希望它每行打印尽可能多的条目,因为它可以容纳在 width 的限制内。

类似这样的:

{   0: 'Data', 1: 'Data', 2: 'Data',
    3: 'Data', 4: 'Data', 5: 'Data',
    ...
    99: 'Data'}

如何使用已经存在的包实现此结果?

【问题讨论】:

  • 请研究漂亮的打印、打印格式和相关主题。一种简单的方法是将join 的所有输出转换为一个字符串,然后将其每行拆分,找到位置width 左侧的第一个逗号空格对。
  • 你介意不使用 pprint 还是必须使用它,因为我相信使用 for 循环应该不难。
  • @Prune 我不傻!我可以轻松编写一些代码来创建我想要的字符串。 pprint 和类似的软件包存在是有原因的。我想要一种简单快捷的方法,可以在任何情况下使用,而不必每次我只想打印一些东西时自己格式化字符串。我编辑了我的问题以使其更清楚。

标签: python dictionary printing pretty-print


【解决方案1】:

这并不能真正回答问题,因为它不使用漂亮的打印或其他现有库。它也不考虑边缘情况,例如键或值中的新行,或嵌套/非字符串类型。

d = dict([(i, 'Data') for i in range(20)])


def print_dict(d, col_width=80, sep=','):
    if not len(d):
        print('{}')
        return
    def get_str(k, v):
        return '%s: %s' % (k, v)


    print('{', end='')
    items = iter(d.items())
    
    entry = get_str(*next(items))
    used_width = len(entry)
    print(entry, end='')

    for k, v in items:
        entry = get_str(k, v)
        
        # if the current entry's string rep will cause an overflow, and the current line
        # isn't blank, then go to the next line
        new_line = used_width + len(entry) > col_width and used_width > 0
        if new_line:
            print(f'{sep}\n', end='')
            used_width = 0
        
        print((f'{sep} ' if not new_line else '') + get_str(k, v), end='')
        used_width += len(entry)

    print('}')

print_dict(d)

它只是将尽可能多的项目放在一行中而不会溢出,但在每一行中至少放置一个项目。

{0: Data, 1: Data, 2: Data, 3: Data, 4: Data, 5: Data, 6: Data, 7: Data, 8: Data, 9: Data, 10: Data,
11: Data, 12: Data, 13: Data, 14: Data, 15: Data, 16: Data, 17: Data, 18: Data, 19: Data}

【讨论】:

    猜你喜欢
    • 2011-03-14
    • 2017-02-22
    • 2015-01-12
    • 2020-10-23
    • 2020-11-10
    • 2022-11-18
    • 2016-09-03
    • 2015-01-22
    • 1970-01-01
    相关资源
    最近更新 更多