如何漂亮地每行打印一个以上的字典条目?

时间:2021-05-07 20:23:46

标签: python dictionary printing pretty-print

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

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

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

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

每行只打印一个条目:

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

但是,我希望它在宽度的限制范围内每行打印尽可能多的条目。

像这样:

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

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

1 个答案:

答案 0 :(得分:0)

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

file1.py

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

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)