【问题标题】:Use of if else inside a dict to set a value to key using Python在 dict 中使用 if else 来使用 Python 将值设置为键
【发布时间】:2019-02-18 20:33:55
【问题描述】:

我正在寻找一种在字典中使用 if else 条件来为键设置值的方法。有什么办法吗?

下面的示例可能会帮助您了解我想要做什么。这不是功能性 Python 代码。只是一个例子给你一个想法。

age = 22
di = {
    'name': 'xyz',
    if age>=18:
        'access_grant': 'yes',
    else:
        'access_grant': 'no',
     }   

【问题讨论】:

    标签: python python-3.x if-statement


    【解决方案1】:

    我认为这将是使用ternary expression 的绝佳机会(python 也将其称为“三元运算符”):

    ...
    di = {
        'name': 'xyz',
        'access_grant': 'yes' if age >= 18 else 'no',
     } 
    ...
    

    【讨论】:

      【解决方案2】:

      您可以使用函数将逻辑与字典分开:

      def access_grant(age):
          if age >= 18:
              return 'yes'
          return 'no'
      
      age = 22
      di = {
          'name': 'xyz',
          'access_grant': access_grant(age),
      }
      

      将逻辑放在字典之外可以更容易地测试和重用。

      【讨论】:

        【解决方案3】:

        在初始定义中设置尽可能多的项目,然后添加其他项目:

        age = 22
        di = {
            'name': 'xyz',
            ... other known keys here
        }
        if age>=18:
            di['access_grant'] = 'yes'
        else:
            di['access_grant'] = 'no'
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-05-02
          • 2016-11-10
          • 2015-04-01
          • 1970-01-01
          • 2019-02-15
          相关资源
          最近更新 更多