How do I assign a value inside list comprehension

Question:

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.

Asked By: Sangita Paul

||

Answers:

Use a normal for loop, not a list comprehension, as you are not trying to create a list of anything.

all_freq = {}
for s in Input:
    if s in all_freq:
        all_freq[s] += 1
    else:
        all_freq[s] = 1

which can be simplified slightly to

all_freq = {}
for s in Input:
    if s not in all_freq:
        all_freq[s] = 0
    all_freq[s] += 1

which can be replaced entirely with

from collections import Counter
all_freq = Counter(Input)
Answered By: chepner

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})
Answered By: Daniel Hao
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.