如何使用Python在降序排序时处理空字符串?
continue
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
get
字典方法避免异常。而且我不建议按循环进行每次迭代时进行分类。最终可以完成。The result for the empty string:
[{'degree': 'BE', 'start_date': '2007-01-01'}, {'degree': 'B.Tech', 'start_date': '' }]
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.The result for the empty string:
[{'degree': 'BE', 'start_date': '2007-01-01'}, {'degree': 'B.Tech', 'start_date': ''}]