Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Print dictionary using column formatting?

I need to print a dictionary containing values

freqs = {',': 1, '8': 3, '0': 3, '6': 1, '7': 2, '!': 1, '+': 2, '#': 8, '%': 4, '.': 1, '&': 7, '/': 1, '1': 3, ')': 2, '"': 1, '-': 2, '3': 6, '5': 1, '$': 1, '2': 2, '*': 4, '4': 2, "'": 1, '9': 1, ':': 1}

This is a dictionary showing a character and the number of times it appears in a string. I want to show it to the user in two columns like so:

, (TAB) 1

8 (TAB) 3

0 (TAB) 3

etc..

Any help would be much appreciated :)

like image 561
Michael Storey Avatar asked Mar 17 '23 20:03

Michael Storey


2 Answers

freqs = {',': 1, '8': 3, '0': 3, '6': 1, '7': 2, '!': 1, '+': 2, '#': 8, '%': 4, '.': 1, '&': 7, '/': 1, '1': 3, ')': 2, '"': 1, '-': 2, '3': 6, '5': 1, '$': 1, '2': 2, '*': 4, '4': 2, "'": 1, '9': 1, ':': 1}

for k , v in freqs.iteritems(): # iterating freqa dictionary
        print k+"\t", v

Output:

!   1
#   8
"   1
%   4
$   1
'   1
&   7
)   2
+   2
*   4
-   2
,   1
/   1
.   1
1   3
0   3
3   6
2   2
5   1
4   2
7   2
6   1
9   1
8   3
:   1

Use comma , after print statement to print keys and values in same line, while \t is used for tabs.

print k+"\t", v
like image 107
Ganesh Pandey Avatar answered Apr 01 '23 00:04

Ganesh Pandey


If you are using Python ≥ 3.6:

freqs = {',': 1, '8': 3, '0': 3, '6': 1, '7': 2, '!': 1, '+': 2, '#': 8, '%': 4, '.': 1, '&': 7, '/': 1, '1': 3, ')': 2, '"': 1, '-': 2, '3': 6, '5': 1, '$': 1, '2': 2, '*': 4, '4': 2, "'": 1, '9': 1, ':': 1}

for k, v in freqs.items():
    print(f'{k:<4} {v}')
like image 24
Brian Spiering Avatar answered Mar 31 '23 22:03

Brian Spiering