Python: print a 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}

      

It is a dictionary showing a character and the number of times it appears in a line. I want to show it to the user in two columns:

, (TAB) 1

8 (TAB) 3

0 (TAB) 3

      

etc..

Any help would be much appreciated :)

+3


source to share


3 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 a comma ,

after printing to print keys and values on the same line, while \t

for tabs.

print k+"\t", v

      

+4


source


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}')

      

+1


source


for item in freqs:
     print item, freqs[item]

      

0


source







All Articles