4

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

3 Answers 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.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
Sign up to request clarification or add additional context in comments.

Comments

1

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 Comment

Thank you for showing the f'{k:<4}' trick. I hadn't seen that before.
0
for item in freqs:
     print item, freqs[item]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.