1

Trying to update/add to a JSON element using if/then statement in python list comprehension. The first part where I'm setting the JSON key 'first_seen' is failing. Any ideas why?

now = datetime.datetime.now().strftime("%B, %d, %Y")
[obj["last_seen"] = now for obj in ref_db if obj['user']==user else add_new(user, ext_source, source, first_seen, now)]

the error is:

[obj["last_seen"] = now for obj in ref_db if obj['user']==user else add_new(user, ext_source, source, first_seen, now)]
                  ^
SyntaxError: invalid syntax

I understand from the error my syntax is wrong, but I can't figure out why it's wrong. Can you not use an equals (=) sign in a list comprehension?

Thanks for the help.

4
  • 1
    It's unclear what result you're expecting. Are you expecting obj["last_seen"] to be the resulting list? Commented Nov 4, 2018 at 13:57
  • 1
    You need a plain if/else statement inside a for loop instead of a list comprehension Commented Nov 4, 2018 at 13:58
  • 1
    Please include a minimal reproducible example that we can actually run. Commented Nov 4, 2018 at 13:59
  • 1
    Possible duplicate of How can I do assignments in a list comprehension? Commented Nov 4, 2018 at 14:00

1 Answer 1

4

List-Comprehensions are for creating lists. You just want to use a for-loop:

now = datetime.datetime.now().strftime("%B, %d, %Y")
for obj in ref_db:
    if obj['user'] == user:
        obj["last_seen"] = now
    else:
        add_new(user, ext_source, source, first_seen, now)
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.