The Python Oracle

Conditionally Add An Attribute To An Dictionary in Python

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Over Ancient Waters Looping

--

Chapters
00:00 Conditionally Add An Attribute To An Dictionary In Python
00:27 Accepted Answer Score 7
00:50 Answer 2 Score 7
00:59 Answer 3 Score 4
01:07 Answer 4 Score 2
01:20 Answer 5 Score 2
01:34 Thank you

--

Full question
https://stackoverflow.com/questions/5679...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 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



ANSWER 2

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



ANSWER 3

Score 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;



ANSWER 4

Score 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