Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally Add An Attribute To An Dictionary in Python

Tags:

python

I want to be able to add an attribute to a dictionary but only if the condition I pass in is true. For example:

def addSum(num):
    obj = {
             'name': "Home",
              'url': "/",
              num > 0 ? 'data': num
    }

Is this possible? I can't find a way to do this in python, I have only seen examples in javascript.

like image 801
Demetrius Avatar asked Aug 24 '26 00:08

Demetrius


1 Answers

obj = {
    'name': 'Home',
    'url': '/',
    **({'data': num} if num > 0 else {})
}

:D

like image 53
MaxCore Avatar answered Aug 26 '26 14:08

MaxCore