Search code examples
pythondictionaryif-statementsyntaxconditional-operator

`SyntaxError` in if-else one-liner


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?


Solution

  • 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