How to print dict in separate line?

前端 未结 6 1764
猫巷女王i
猫巷女王i 2020-12-06 14:20
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 (w         


        
相关标签:
6条回答
  • 2020-12-06 14:39

    Another complex way using lambda

    f = lambda *x: null; 
    f( *( print( x,":",y ) for x,y in mydict.iteritems() ) )
    

    Output

    key2 : 2
    key1 : 1
    
    0 讨论(0)
  • 2020-12-06 14:52
    >>>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
    
    0 讨论(0)
  • 2020-12-06 14:54

    no need to use any additional function, use simple for loop,

    student = {"Name":"Chandler Bing","Age":24,"Subject":["Sarcasm","Joke"]}
    print(student)
    for i in student:
        print(i,":",student[i])
    
    Name : Chandler Bing
    Age : 24
    Subject : ['Sarcasm', 'Joke']
    
    0 讨论(0)
  • 2020-12-06 14:57

    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)
    
    0 讨论(0)
  • 2020-12-06 15:02

    Python 3 - method name and syntactical updates - nice collection of swizzles

    1 - lambdas are throw-away anonymous functions mainly used with filter, map, reduce etc.
    Here were are creating a function containing a print and key,value iteration.

    f = lambda *x: None; 
    f( *( print( x,":",y ) for x,y in genre_counting.items() ) )
    
    Games : 3862
    Productivity : 178
    Weather : 72
    Shopping : 122
    Reference : 64
    Finance : 104
    

    2 - repr() returns the canonical string representation of the object.

    for x in genre_counting:
    print(repr(x),":",genre_counting[x])
    
    'Games' : 3862
    'Productivity' : 178
    'Weather' : 72
    'Shopping' : 122
    'Reference' : 64
    'Finance' : 104
    

    3 - %s is a string placeholder; %i is an integer placeholder

    for k, v in genre_counting.items():
    print( '%s : %i' % (k, v) )
    
    Games : 3862
    Productivity : 178
    Weather : 72
    Shopping : 122
    Reference : 64
    Finance : 104
    
    0 讨论(0)
  • 2020-12-06 15:03
    >>> from pprint import pprint
    >>> pprint(sums)
    {'air': 2,
     'and': 1,
     'at': 3,
     'be': 1,
     'body': 1,
     ....., # and so on...
     'you': 2}
    
    0 讨论(0)
提交回复
热议问题