Home > Software design >  Changing a for loop to a dictionary comprehension
Changing a for loop to a dictionary comprehension

Time:04-02

I get how to do regular comprehension style conversions for For loops, but this, I can't wrap my head around.

I know that normally you would change the lines 3-5 into one line, but is it possible to include the empty list in the comprehension?

The code is

    text = input().lower()
    dict = {}
     for x in text:
      if x.isalpha()
       dict[x] = text.count(x)
    print(dict)

I don't even know where to get started.

CodePudding user response:

Don't use dict as a variable name, it's the name of a built-in function.

To convert the loop to a dictionary comprehension, change dict[key] = value to key: value, then follow it with the for loop and if condition.

text_dict = {x: text.count(x) for x in text if x.isalpha}

Note that Python has a standard library function collections.Counter() that does this.

from collections import Counter

text_dict = Counter(filter(str.isapha, text))

CodePudding user response:

By referring to the dictionary comprehension posted by @Barmar, another way to do so is using dictionary comprehension and set:

result = dict((x,text.count(x)) for x in set(text.lower()) if x.isalpha)
  • Related