Python if 语句在创建字典时跳过字典键

Python if statement to skip dictionary key when creating a dictionary

我的代码如下所示:

def createEventBody(name,description,attendees,location, eventColor = None):
    eventBody = {
              'Name': name, #EventName
              'Color': eventColor,
              'location': location,
              'description':description,
              'attendees': [],
              }

问题是,我想添加一些逻辑,以便在 eventColor = None 时不包括键 'Color'。 我在想这样的事情:

def createEventBody(name,description,attendees,location, eventColor = None):
    eventBody = {
              'Name': name, #EventName
              ('Color': eventColor) if eventColor != None else pass,
              'location': location,
              'description':description,
              'attendees': [],
              }

但是 'pass' 不允许我“跳过”那个键。 我该如何解决这个问题?

x if y else z 是一个条件表达式:它是一种根据条件发出值的方法。它不适合做某事或不做。这就是 if 语句的用途。

在创建 eventBody dict 后在 if 语句中设置 Color 条目。

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?

是的。您可以在字典中设置所有这些条目,然后忽略值为 None.

的条目

像这样:

eventBody = {
          'Name': name,
          'Color': eventColor,
          'location': location,
          'description':description,
          'attendees': [],
}

eventBody = {k:v for (k,v) in eventBody.items() if v is not None}

或者如果你只想过滤一些特定的键,像这样:

for key in ('Color', 'location', 'description'):
    if eventBody[key] is None:
        del eventBody[key]

pass 不是表达式,它没有值。我会坚持原来的(即设置 'Color': None),但如果你不想 None,你可以只做一个标准的 if 语句。

你可以使用dict.update方法

   eventBody = {
              'Name': name, #EventName
              'location': location,
              'description':description,
              'attendees': [],
              }
if eventColor:
    eventBody.update({"Color": eventColor})

不能在字典中使用 if 语句。

但是,这会完成您的工作。

eventBody = {
      'Name': name,
      'location': location,
      'description':description,
      }
if eventColor:
    eventBody.update(Color=eventColor)