我一直想整齐地打印一本字典,所以我把它掀起了:
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 = ' ')
这样打印出来:
Col1 Col2 Col3
test0 1 2
test1 3 4
test2 5 6
test3 7 8
test4 9 10
有没有什么方法可以定义一个函数,如果我调用它会这样做?我不想在我需要的时候在我的程序中使用这个代码。我已经尝试了一些东西,但我似乎无法做出正常工作的东西。
答案 0 :(得分:1)
这是一个相当普遍的变体:
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()
根据您想要打印的所有dict
的约束条件,代码将需要简化或进一步复杂化。例如,此版本适用于任何值为列表的字典。如果您准确且严格地指定 dict
您希望能够以这种方式打印,则代码(如果需要)可以相应地更改。
答案 1 :(得分:0)
只需将已有的代码放入函数定义中,如下所示:
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 = ' ')
然后你可以像这样使用它:
test = {
"test0": [1, 2],
"test1": [3, 4],
"test2": [5, 6],
"test3": [7, 8],
"test4": [9, 10]
}
print_dict(test)