python syntax error in dict comprehension -


here i'm trying do:

i want count letters frequency in sentence.

here code in python far:

for in line:     if in my_count.keys():         my_count[i]+=1     else:         my_count[i]=1 

is there way fulfill same goal dict comprehension, same list comprehension?

i have thought @ such :

my_count = { x:(my_count[x]+=1) x in line if x in my_count else x:1 } 

but not pass syntax check (syntaxerror: invalid syntax @ +=).

thanks , advices!

counter in collections seems accomplish this.

in [1]: line = 'the quick brown fox jumps on lazy dog' in [2]: collections import counter in [3]: c = counter(line) in [4]: c out[4]: counter({' ': 8, 'o': 4, 'e': 3, 'h': 2, 'r': 2, 'u': 2, 't': 2, 'a': 1, 'c': 1, 'b': 1, 'd': 1, 'g': 1, 'f': 1, 'i': 1, 'k': 1, 'j': 1, 'm': 1, 'l': 1, 'n': 1, 'q': 1, 'p': 1, 's': 1, 'w': 1, 'v': 1, 'y': 1, 'x': 1, 'z': 1}) 

Comments

Popular posts from this blog

c++ - How to add Crypto++ library to Qt project -

jQuery Mobile app not scrolling in Firefox -

How to use vim as editor in Matlab GUI -