Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I assign a value inside list comprehension

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Could you please help me.

>Solution :

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})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading