Conditionally Add An Attribute To An Dictionary in Python

Question:

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.

Asked By: Demetrius

||

Answers:

Just add/check it in separate statement:

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

print(addSum(3))   # {'name': 'Home', 'url': '/', 'data': 3}
print(addSum(0))   # {'name': 'Home', 'url': '/'}
Answered By: RomanPerekhrest

Create the dictionary without the optional element, then add it in an if statement

def addSum(num):
    obj = {
        'name': "Home",
        'url': "/"
    }
    if num > 0:
        obj['data'] = num;
Answered By: Barmar

Yes, just create the dictionary without the attribute, then create an if statement to add it if the condition is true:

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

    return obj
Answered By: Matt

You can’t do it with quite that syntax. For one thing, you need Python, not Java/C.

(1) add the attribute, but set to None:

obj = {'name': "Home",
       'url': "/",
       'data': num if num > 0 else None
      }

(2) make it an add-on:

obj = {'name': "Home",
       'url': "/"}
if num > 0:
    obj['data'] = num
Answered By: Prune
obj = {
    'name': 'Home',
    'url': '/',
    **({'data': num} if num > 0 else {})
}

😀

Answered By: MaxCore
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.