如何在使用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存在,则上述代码有效:

用例1(如果存在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:-

KeyError:"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': ''}]

相关内容

  • 没有找到相关文章

最新更新