LukeK15
LukeK15

Reputation: 33

Defining a function that prints dictionaries neatly

I've been wanting to print a dictionary neatly, so I whipped this up:

test = {
    "test0": [1, 2],
    "test1": [3, 4],
    "test2": [5, 6],
    "test3": [7, 8],
    "test4": [9, 10]
}

keys = list(test.keys())
keys.sort()
print("Col1      Col2  Col3")
for x in range(5):
    check_1 = (test["test{0}".format(x)][0])
    check_2 = (test["test{0}".format(x)][1])
    print("test{0}".format(x), check_1, check_2, sep = '     ')

This prints thusly:

Col1      Col2  Col3
test0     1     2
test1     3     4
test2     5     6
test3     7     8
test4     9     10

Is there any way I can define a function that will do this if I call it? I don't want to have to fit this code in my program whenever I may need it. I've tried a few things, but I can't seem to be able to make something that works properly.

Upvotes: 0

Views: 208

Answers (2)

Alex Martelli
Alex Martelli

Reputation: 881635

Here's a reasonably-general variant:

def print_dict_of_lists(adict):
    # formatting the header: by far the hardest part!
    ncols = max(len(v) for v in adict.values())
    colw = max(len(str(c)) for v in adict.values() for c in v)
    khw = max(len(str(k)) for k in adict)
    print('{:{khw}} '.format('Col1', khw=khw), end='')
    for i in range(ncols):
        print('Col{:<{colw}} '.format(i+2, colw=colw-3), end='')
    print()
    # next, the easier task of actual printing:-)
    for k in sorted(adict):
        print('{:{khw}} '.format(k, khw=khw), end='')
        for c in adict[k]:
            print('{:<{colw}} '.format(c, colw=colw), end='')
        print()

Depending on what constraints apply to all dicts you want to print, the code will require simplification or further complexity. This version should work for any dictionary whose values are lists, for example. If you specify exactly and rigorously what dicts you want to be able to print this way, the code, if need be, can be altered accordingly.

Upvotes: 1

Raydel Miranda
Raydel Miranda

Reputation: 14360

Just put the code you already have into a function definition, like this:

def print_dict(dict_):
    keys = list(dict_.keys())
    keys.sort()
    print("Col1      Col2  Col3")
    for x in range(5):
        check_1 = (dict_["test{0}".format(x)][0])
        check_2 = (dict_["test{0}".format(x)][1])
        print("test{0}".format(x), check_1, check_2, sep = '     ')

then you can use it like this:

test = {
    "test0": [1, 2],
    "test1": [3, 4],
    "test2": [5, 6],
    "test3": [7, 8],
    "test4": [9, 10]
}

print_dict(test)

Upvotes: 0

Related Questions