Printing dictionary pair and next iteration's pair on one line in columns

I have a long list of 100+ unique (names don’t repeat) key/value pairs which I’d like to print consolidated into two equal width columns.

  • How do I get the next iteration’s key/value? (i.e. How do I print two key/value pairs in the same iteration?)
  • How do I get the pairs to print in two columns of 40 character width or the
    max width of the longest length of a pair?

Current loop:

for key in example:
    print(f'{key}: {example[key]}')

Example dictionary:

example = {
    'key0': 'val0',
    'key1': 'val1',
    'key2': 'val2',
    'key3': 'val3',
    'key4': 'val4',
    'key5': 'val5'

Desired result:

key0: val0            key1: val1
key2: val2            key3: val3
key4: val4            key5: val5

>Solution :

you can run over the list of keys two by two

keys = list(example.keys())
for i in range(0,len(keys),2):
    key1 = keys[i]
    key2 = keys[i+1]
    print("%s:%s       %s:%s"%(key1,example[key1],key2,example[key2]))


key0:val0       key1:val1
key2:val2       key3:val3
key4:val4       key5:val5

Leave a Reply