My code looks like this:
def createEventBody(name,description,attendees,location, eventColor = None):
eventBody = {
'Name': name, #EventName
'Color': eventColor,
'location': location,
'description':description,
'attendees': [],
}
The thing is, I want to add some logic so that the key ‘Color’ is not included if eventColor = None.
I was thinking something like this:
def createEventBody(name,description,attendees,location, eventColor = None):
eventBody = {
'Name': name, #EventName
('Color': eventColor) if eventColor != None else pass,
'location': location,
'description':description,
'attendees': [],
}
However ‘pass’ doesn’t allow me to "skip" that key.
How could I fix this?
>Solution :
x if y else z is a conditional expression: it is a way of issuing a value that depends on a condition. It is not suitable for doing something or not doing it. That is what an if statement is for.
Set the Color entry in an if statement after the eventBody dict is created.
eventBody = {
'Name': name,
'location': location,
'description':description,
'attendees': [],
}
if eventColor is not None:
eventBody['Color'] = eventColor
is there a way to do this but for multiple variables without the use of multiple if statements? So instead of doing color is not None, description is not None doing it all with one single expression?
Yes. You could set all those entries in your dictionary, and then omit the ones that have the value None.
Something like this:
eventBody = {
'Name': name,
'Color': eventColor,
'location': location,
'description':description,
'attendees': [],
}
eventBody = {k:v for (k,v) in eventBody.items() if v is not None}