user4691770
user4691770

Reputation:

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

I have a dictionary with lists stored as the values:

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

What I would like to do is iterate through all of these to display a table:

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

I know I can use the zip function like:

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

but I want to learn how to iterate through this sort of thing without using zip. I've tested a few nested for loops and I can't get the output I want!!

Upvotes: 0

Views: 481

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195543

You can use this example to iterate over the my_dict, but using the zip() is more pythonic (and convenient too):

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

Prints:

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

EDIT: To specify the order of columns, you can use 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))

Prints:

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

Upvotes: 1

Related Questions