Conditionally Add An Attribute To An Dictionary in Python
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Mysterious Puzzle
--
Chapters
00:00 Question
00:35 Accepted answer (Score 4)
01:02 Answer 2 (Score 3)
01:21 Answer 3 (Score 2)
01:41 Answer 4 (Score 2)
01:58 Thank you
--
Full question
https://stackoverflow.com/questions/5679...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Mysterious Puzzle
--
Chapters
00:00 Question
00:35 Accepted answer (Score 4)
01:02 Answer 2 (Score 3)
01:21 Answer 3 (Score 2)
01:41 Answer 4 (Score 2)
01:58 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