简体   繁体   English

Python,对字典列表进行排序

[英]Python, sorting a dictionary list

I'm having trouble sorting out a dictionary key/value. 我在整理字典键/值时遇到麻烦。 Basically, this is what I'm trying to achieve: (This works) 基本上,这就是我要实现的目标:(这可行)

>>> dict = {}
>>> dict['pens'] = ['234sdf, gjjhj', 'asd123, fghtert', '652efg, vbn456h']
>>> dict['pens'] = sorted(dict['pens'])
>>> print('Sorted: ', dict['pens'])
Sorted:  ['234sdf, gjjhj', '652efg, vbn456h', 'asd123, fghtert']

Now in my actual script, I get an error: 现在在我的实际脚本中,我得到一个错误:

>>> grpProfile['students'] = sorted(grpProfile['students'])
TypeError: unorderable types: NoneType() < NoneType()
type(grpProfile['students']) # returns list
type(grpProfile['students'][0] )# returns string

This also displays the list of strings. 这也会显示字符串列表。

for s in grpProfile['students']:
  print(s)

What could be wrong with my code? 我的代码有什么问题? I'm completely lost. 我完全迷路了。 Every test I've done is working. 我所做的每项测试都有效。

As ajcr has correctly pointed out, it seems that at least one element in your list is NoneType() type, ie you have a None object (maybe a variable you have not set). 正如ajcr正确指出的那样,列表中似乎至少有一个元素是NoneType()类型,即您有一个None对象(可能是尚未设置的变量)。

Get rid of them, and then sort your list of values. 摆脱它们,然后对值列表进行排序。 To create a list without instances of that type: 要创建没有该类型实例的列表:

[x for x in list if x is not None]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM