Home > Software design >  Ternary operator python not working on dict assignment
Ternary operator python not working on dict assignment

Time:02-08

I'm new to python.

Today i'm trying to simplify this:

        for x in t:
            if x in hash:
                hash[x]  = 1
            else:
                hash[x] = 1

To this:

        for x in t:
            hash[x]  = 1 if x in hash else hash[x] = 1

Then i got an error:

SyntaxError: invalid syntax
                                           ^
    hash[x]  = 1 if x in hash else hash[x] = 1
Line 8  (Solution.py)

I thought i'm doing an expression here? as shown in this question

What am i doing wrong?

CodePudding user response:

The ternary operator returns a value, it does not support an assignment as a value (otherwise it would be a regular if/then/else)

You can use it like this:

hash[x] = hash[x]   1 if x in hash else 1

BTW hash is a Python built-in function, you should not use that as a variable name.

Note that there are other data structures in Python that might be better suited to your purpose. (e.g. collections.Counter, collections.defaultdict)

CodePudding user response:

Try this:

for x in t:
    hash[x] = hash.get(x, 0)   1 

  •  Tags:  
  • Related