Demetrius
Demetrius

Reputation: 451

Conditionally Add An Attribute To An Dictionary in 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.

Upvotes: 6

Views: 6573

Answers (5)

MaxCore
MaxCore

Reputation: 2738

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

:D

Upvotes: 8

Prune
Prune

Reputation: 77860

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

Upvotes: 7

Matt
Matt

Reputation: 982

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

Upvotes: 2

Barmar
Barmar

Reputation: 782130

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;

Upvotes: 2

RomanPerekhrest
RomanPerekhrest

Reputation: 92884

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

Upvotes: 4

Related Questions