Home > Net >  Print key value pairs from a dictionary
Print key value pairs from a dictionary

Time:06-06

I want to pretty-print the key-value pairs of a dictionary. I have the following code:

dict = {'AAAAA': 2, 'BB': 1, 'CCCCCCCCC': 85}

for k, v in dict.items():
    print('{}........{}'.format(k, v))

This is what my code currently produces:

AAAAA........2
BB........1
CCCCCCCCC........85

But I want:

AAAAA............2
BB...............1
CCCCCCCCC........85

How do I make this happen?

CodePudding user response:

Using f-string you can set the width of each field and pad with .

#! /usr/bin/env python3
dict = {'AAAAA': 2, 'BB': 1, 'CCCCCCCCC': 85}

for k, v in dict.items():
    print(f'{k:.<10}{v:.>10}')

giving

AAAAA..............2
BB.................1
CCCCCCCCC.........85

or

    print(f'{k:.<20}{v}')

if you really want

AAAAA...............2
BB..................1
CCCCCCCCC...........85

CodePudding user response:

You can use str.ljust():

dictionary = {'AAAAA': 2, 'BB': 1, 'CCCCCCCCC': 85}
n = 17

for key, value in dictionary.items():
    justified_key = key.ljust(n, ".")
    print(f"{justified_key}{value}")

This outputs:

AAAAA............2
BB...............1
CCCCCCCCC........85

CodePudding user response:

Consider using len() to balance out the number of dots

dict = {'AAAAA': 2, 'BB': 1, 'CCCCCCCCC': 85}

total = 15
for k, v in dict.items():
    print(k, "." * (total - len(k)), v, sep="")

CodePudding user response:

It adapts to the length of your k,v:

dict = {'AAAAA': 2, 'BB': 1, 'CCCCCCCCC': 85}

for k, v in dict.items():
    print(f'{k}{(20-(len(k) len(str(v))))*"."}{v}')

AAAAA..............2
BB.................1
CCCCCCCCC.........85
  • Related