Python 3 使用列表值遍历字典以显示为 table

Python 3 iterate through dictionary with list values to display as table

我有一个字典,其中的列表存储为值:

my_dict = {"version":[1, 2, 3],"size":[10, 20, 30],"cost":["£200","£350","£400"],"limit":[44, 53, 62, 71],}

我想做的是遍历所有这些以显示 table:

version  size   cost    limit
  1       10    £200     44         
  2       20    £350     53
  3       30    £400     62

我知道我可以像这样使用 zip 功能:

for row in zip(*([key] + (value) for key, value in sorted(my_dict.items()))):
    print(*row)

但我想了解如何在不使用 zip 的情况下迭代此类内容。我已经测试了几个嵌套的 for 循环,但无法得到我想要的输出!!

您可以使用此示例迭代 my_dict,但使用 zip() 更符合 Python 风格(也很方便):

my_dict = {"version":[1, 2, 3],"size":[10, 20, 30],"cost":["£200","£350","£400"],"limit":[44, 53, 62, 71],}

print(''.join('{:^15}'.format(k) for k in my_dict))

cnt = 0
while True:
    try:
        for k in my_dict:
            print('{:^15}'.format(my_dict[k][cnt]), end='')
        print()
        cnt += 1
    except IndexError:
        break

打印:

version         size           cost           limit     
   1             10            £200            44       
   2             20            £350            53       
   3             30            £400            62       

编辑:要指定列的顺序,您可以使用 operator.itemgetter:

my_dict = {"version":[1, 2, 3],"size":[10, 20, 30],"cost":["£200","£350","£400"],"limit":[44, 53, 62, 71],}

from operator import itemgetter

columns = ['version', 'cost', 'limit', 'size']

print(''.join('{:^15}'.format(k) for k in columns))

i = itemgetter(*columns)
for vals in zip(*i(my_dict)):
    print(''.join('{:^15}'.format(v) for v in vals))

打印:

version         cost           limit          size      
   1            £200            44             10       
   2            £350            53             20       
   3            £400            62             30