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.

1 Answers1

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)
Daniel
  • 42,087
  • 4
  • 55
  • 81