0

I wrote this block of code, but it doesn't work because of SyntaxError.

def char_freq(message):
    d = dict()
    for ch in message:
        d[ch] += 1 if ch in d else d[ch] = 1
    return d                             ^ SyntaxError: End of statement expected

I don't know how to rewrite the expression in order to keep if-else in one line and to get it to work.

I know it is possible to implement the function as a simple for loop, but I don't understand, why my if-else one-liner results in SyntaxError?

2 Answers2

2

Turn d into a defaultdict and then you can just ignore the statement altogether

from collections import defaultdict
def char_freq(message):
    d = defaultdict(int)
    for ch in message:
        d[ch] += 1
    return d     

It also looks like you're just counting characters so you could just use a counter

from collections import Counter
def char_freq(message):
    return Counter(message)
Sayse
  • 42,633
  • 14
  • 77
  • 146
1

As you asked to keep the if/else Do

d[ch] = (d[ch] + 1) if ch in d else 1

But the dict.get() syntax is nicer d[ch] = d.get(ch, 0) + 1

Or a collections.defaultdict with int factory

def char_freq(message):
    d = defaultdict(int)
    for ch in message:
        d[ch] += 1
    return d
azro
  • 53,056
  • 7
  • 34
  • 70