0

I use lambda functions in Python a lot. All of a sudden, I cannot figure out why is there a syntax error message for this:

table['sp1 name'] = table['sp1'].apply(lambda x: sp1_new_dict[x] if x in sp1_new_dict.keys())

Any ideas? Thanks!

4
  • 3
    You're missing an else in the ternary if statement Commented Nov 29, 2022 at 17:06
  • 1
    Please update your question with the full error traceback. Commented Nov 29, 2022 at 17:07
  • simply, sp1_new_dict[x] if x in sp1_new_dict.keys() is not a valid expression, thus it cannot go there, hence the SyntaxError Commented Nov 29, 2022 at 17:07
  • lambda function must have a return value for every valid input hence the else expression must be provided Commented Nov 29, 2022 at 17:12

1 Answer 1

2

You need an else. Boiling down your error:

x = 1 if True

  File "<stdin>", line 1
    x = 1 if True
                 ^
SyntaxError: invalid syntax


# No error here
x = 1 if True else 2

Since you are using a dictionary, maybe use dict.get:

table['sp1 name'] = table['sp1'].apply(lambda x: sp1_new_dict.get(x))

Which returns None if the key isn't present

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.