standarduser
standarduser

Reputation: 86

Update JSON element in Python List Comprehension

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.

Upvotes: 1

Views: 275

Answers (1)

Daniel
Daniel

Reputation: 42748

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)

Upvotes: 4

Related Questions