简体   繁体   中英

Print key value pairs from a dictionary

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?

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

You can usestr.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

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

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="")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM