I write a small program using comprehension list python and I need to assign a value to dictionary.
It gives me syntax error.
JavaScript
x
4
1
all_freq = {}
2
Input = 'google.com'
3
[all_freq[s] += 1 if s in Input else all_freq[s] = 1 for s in Input]
4
It says “[” was not closed.
Could you please help me.
Advertisement
Answer
Just inspired by earlier post, you can also do this way:
Of course, Counter is the best to do quick tallying.
JavaScript
1
10
10
1
from collections import defaultdict
2
3
all_freq = defaultdict(int) # initialize the dict to take 0, if key is not existing yet
4
5
for s in 'google': # each for-loop, just increment the *count* for corresponding letter
6
all_freq[s] += 1
7
8
print(all_freq)
9
defaultdict(<class 'int'>, {'g': 2, 'o': 2, 'l': 1, 'e': 1})
10