Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]))

output:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading