使用 python 降序排序时如何处理空字符串?

How to handle empty string while sorting in descending order using python?

我在下面有一个词典列表

profile = {
          "education": [
            {
              "degree": "B.Tech",
              "start_date": "2003-01-01"
            },
            {
              "degree": "BE",
              "start_date": "2007-01-01"
            }
          ]
        }

我正在按降序排列 start_date

代码:

temp = []
if 'education' in profile:
    for info in (profile['education']):
      temp.append(info)
      null_values = {""}
      sorted_date = sorted(temp, key=lambda x: x["start_date"] if x["start_date"]
                                        not in null_values else "9999-99-99", reverse=True)
    print(sorted_date)

如果 start_date 存在,以上代码有效:

Usecase1(如果start_date存在):

profile = {
              "education": [
                {
                  "degree": "B.Tech",
                  "start_date": "2003-01-01"
                },
                {
                  "degree": "BE",
                  "start_date": "2007-01-01"
                }
              ]
            }

O/p:-

[{'degree': 'BE', 'start_date': '2007-01-01'}, {'degree': 'B.Tech', 'start_date': '2003-01-01'}]

用例2(如果start_date值为空):

profile = {
          "education_details": [
            {
              "degree": "B.Tech",
              "start_date": ""
            },
            {
              "degree": "BE",
              "start_date": "2007-01-01"
            }
          ],
        }

O/P:-

[{'degree': 'B.Tech', 'start_date': ''}, {'degree': 'BE', 'start_date': '2007-01-01'}]

注意:如果start_date值为空,则将此项放在末尾。

预期O/P:-

[{'degree': 'BE', 'start_date': '2007-01-01'},{'degree': 'B.Tech', 'start_date': ''}]

用例(检查start_date是否存在):

profile = {
          "education_details": [
            {
              "degree": "B.Tech",
              # "start_date": ""
            },
            {
              "degree": "BE",
              "start_date": "2007-01-01"
            }
          ],
        }

O/P:-

按键错误:'start_date'

预期o/p:-

[{'degree': 'BE', 'start_date': '2007-01-01'}, {'degree': 'B.Tech'}]

请帮帮我,伙计们。

使用字典的get方法来规避异常。而且我不建议每次循环迭代时都进行排序。最终可以做到这一点。

temp = []
if 'education' in profile:
    for info in (profile['education']):
        temp.append(info)
    null_values = {""}
    sorted_date = sorted(temp,
                         key=lambda x: x.get("start_date", "0000-00-00"),
                         reverse=True)
    print(sorted_date)

空字符串的结果:

[{'degree': 'BE', 'start_date': '2007-01-01'}, {'degree': 'B.Tech', 'start_date': ''}]