Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python if statement to skip dictionary key when creating a dictionary

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading