6

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.

Demetrius
  • 449
  • 1
  • 9
  • 20
  • 2
    `obj` is a dictionary, not an object. – Barmar Jun 27 '19 at 20:11
  • Can you add the javascript equivalent that you had in mind as well? What you posted is not valid js. Don't know of any similar syntax in javascript but it would be cool :) – André Laszlo Jun 27 '19 at 20:13
  • 1
    lots of examples on here, here is one https://stackoverflow.com/questions/11704267/in-javascript-how-to-conditionally-add-a-member-to-an-object/38483660 – Demetrius Jun 27 '19 at 20:16

5 Answers5

6

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
Prune
  • 76,765
  • 14
  • 60
  • 81
3

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': '/'}
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
3
obj = {
    'name': 'Home',
    'url': '/',
    **({'data': num} if num > 0 else {})
}

:D

MaxCore
  • 2,438
  • 4
  • 25
  • 43
2

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;
Barmar
  • 741,623
  • 53
  • 500
  • 612
2

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
Matt
  • 972
  • 3
  • 11
  • 22