Sorting list containing value:None, results to TypeError: '<' not supported between instances of 'NoneType' and 'str'

Sorting list containing value:None, results to TypeError: '<' not supported between instances of 'NoneType' and 'str'

我的字典包含 key:value 对列表。如何对包含 key:value 对的列表进行排序(其中值为 None

from operator import itemgetter
test = {"test":[{ "name" : "Nandini", "age" : 20}, { "name" : "Manjeet", "age" : 20 }, { "name" : None , "age" : 19 }] }
print(sorted(test["test"], key=itemgetter('name')) )

结果 TypeError: '<' not supported between instances of 'NoneType' and 'str'

输出应包含 None 个值,类似于:[{ "name" : None , "age" : 19 }, { "name" : "Manjeet", "age" : 20 },{ "name" : "Nandini","age" : 20}]

您可以使用 "or" 技巧:

# python 2 you can use with the itemgetter('name') 
# python3 needs a lambda, see further below
from operator import itemgetter
test = {"test":[{ "name" : "Nandini", "age" : 20}, 
                { "name" : "Manjeet", "age" : 20 }, 
                { "name" : None , "age" : 19 }] }


# supply a default value that can be compared - here "" is a good one
print(sorted(test["test"], key=itemgetter('name') or "") )

获得:

[{'age': 19, 'name': None}, 
 {'age': 20, 'name': 'Manjeet'}, 
 {'age': 20, 'name': 'Nandini'}]

您实质上为 None 提供了一个默认值(和空字符串 - 它对值的真实性进行操作)。

对于 python 3 你需要使用 lambda 代替:

print(sorted(test["test"], key=lambda x: x['name'] or ""  ))  

更多信息:

  • Why are Python lambdas useful?

这里的 lambda 有点像 itemgetter() - x 是列表的每个内部字典,x["name"] 是你想要作为键的值,如果它是 Falsy (None, "") 它将使用您在 or:

之后提供的任何内容
print(None or "works")
print("" or "works as well")