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.

3
  • 2
    obj is a dictionary, not an object. Commented Jun 27, 2019 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 :) Commented Jun 27, 2019 at 20:13
  • 1
    lots of examples on here, here is one stackoverflow.com/questions/11704267/… Commented Jun 27, 2019 at 20:16

5 Answers 5

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

:D

Sign up to request clarification or add additional context in comments.

Comments

7

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

4 Comments

So in the first example the condition has to go after the value?
Yes. See any tutorial on the Python ternary operator.
the 1st example will throw SyntaxError
Thanks; fixed the missing quotation mark and tested with cut-and-paste.
4

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': '/'}

Comments

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;

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.