Joohwan
Joohwan

Reputation: 2512

Add item to python dictionary if the bool(item) is True

I want to add an item to a dictionary only if the bool(item) evaluates to True:

if item_to_add:
    d["name_of_item"] = item_to_add

Is there a way to do this in 1 line? Thanks.

Upvotes: 1

Views: 1191

Answers (1)

cdhowie
cdhowie

Reputation: 169028

Yes, there is:

if item_to_add: d["name_of_item"] = item_to_add

Upvotes: 5

Related Questions