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

Time:04-04

I have a list of dictionaries below

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

I was sorting the start_date in descending order

code:

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)

The above code is working if start_date exists:

Usecase1(If start_date exists):

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'}]

Use case2(If start_date value is empty):

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'}]

Note: If the start_date value is empty, place this item at the end.

Expected O/P:-

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

Use case(check if start_date exists or not):

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

O/P:-

KeyError: 'start_date'

Expected o/p:-

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

Please help me, guys.

CodePudding user response:

Use get method of dictionaries for eluding of exceptions. And I do not recommend to sort every time per iteration in loop. This can be done in the end.

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)

The result for the empty string:

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

  • Related