def myFUNC (e):
return e["Points"]
team_stats = [
{"76ers" : {"Wins" : 22,
"Losses" : 12,
"Points" : 647},
"Nets" : {"Wins" : 22,
"Losses" : 13,
"Points" : 629},
"Bucks" : {"Wins" : 21,
"Losses" : 13,
"Points" : 618}}
]
print(team_stats.sort(key=myFUNC))
KeyError: 'Points'
获取
KeyError
的原因是,您试图从字典的外部级别访问键"Points"
,该键不属于该级别,即使它属于当前结构,您也不会看到结果上的差异在一个}s in Python are guaranteed to maintain order 。如果确实满足版本要求,则使用:
list
中有一个dict
,没有什么要sort
。如果要对dict
进行排序,则只有在使用3.7+
时才可能,因为从3.7
开始,^{给
如果不满足版本要求,则需要使用^{} :
其中:
但我不明白你为什么需要这个清单
另外,
list().sort()
修改list
的位置,这不仅在这里是无用的,打印它将返回None
我想你的意思是这可能
您可以按点对每个名称进行排序
问题是列表中有一个字典,所以当您尝试对列表进行排序时,它会查看外部字典,而不是内部字典
解决方案是只使用字典项,如下所示:
相关问题 更多 >
编程相关推荐