I write a small program using comprehension list python and I need to assign a value to dictionary.
It gives me syntax error.
all_freq = {} Input = 'google.com' [all_freq[s] += 1 if s in Input else all_freq[s] = 1 for s in Input]
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.
from collections import defaultdict all_freq = defaultdict(int) # initialize the dict to take 0, if key is not existing yet for s in 'google': # each for-loop, just increment the *count* for corresponding letter all_freq[s] += 1 print(all_freq) defaultdict(<class 'int'>, {'g': 2, 'o': 2, 'l': 1, 'e': 1})