How to print dict in separate line?

17,470

Solution 1

>>> from pprint import pprint
>>> pprint(sums)
{'air': 2,
 'and': 1,
 'at': 3,
 'be': 1,
 'body': 1,
 ....., # and so on...
 'you': 2}

Solution 2

>>>for x in sums:
    print(repr(x),":",dic[x])


'and' : 1
'heart' : 1
'sussex' : 1
'rise' : 1
'love' : 2
'be' : 1
'may' : 2
'the' : 1
'is' : 1
'in' : 3
'body' : 1
'rest' : 1
'at' : 3
'pass' : 1
'not' : 3
'knee' : 1
'air' : 2
'bury' : 3
'tongue' : 1
'lie' : 1
'winchelsea' : 1
'i' : 5
'there' : 1
'grass' : 1
'quiet' : 1
'shall' : 4
'montparnasse' : 1
'fresh' : 1
'easy' : 1
'wounded' : 1
'you' : 2
'champmedy' : 1
'my' : 3

Solution 3

You could use iteritems to iterate through keys and values and thus be able to format the output as you want. Assuming strings as keys and ints as values:

for k, v in d.iteritems():
    print '%s: %d' % (k, v)
Share:
17,470
ThanaDaray
Author by

ThanaDaray

Ask me m(^,...,^)m

Updated on July 16, 2022

Comments

  • ThanaDaray
    ThanaDaray almost 2 years
    import re
    sums = dict()
    fh= open('wordcount.txt','r')
    for line in fh:
        words = [word.lower() for word in re.findall(r'\b\w+\b', line)]
        for word in (words):
            if word in sums:
                sums[word] += 1
            else:
                sums[word] = 1
    print sums
    fh.close
    

    result shows

    {'and': 1, 'heart': 1, 'love': 2, 'is': 1, 'pass': 1, 'rest': 1, 'wounded': 1, 'at': 3, 
    'in': 3, 'lie': 1, 'winchelsea': 1, 'there': 1, 'easy': 1, 'you': 2, 'body': 1, 'be': 
    1, 'rise': 1, 'shall': 4, 'may': 2, 'sussex': 1, 'montparnasse': 1, 'not': 3, 'knee': 
    1, 'bury': 3, 'tongue': 1, 'champmedy': 1, 'i': 5, 'quiet': 1, 'air': 2, 'fresh': 1, 
    'the': 1, 'grass': 1, 'my': 3}
    

    The code print all the word and count frequency word use.

    I would like to print dict in separate line.

    'and': 1
    'heart': 1
    'love': 2
    ...
    

    Any possible way to do that?