我正在尝试根据键“订单”对此词典进行排序。请找下面的样本字典: -
{'about-us': [{'name': 'CONSTITUTION', 'order': u'2', 'uri': 'constitution'},
{'name': 'EXECUTIVE COMMITTEE',
'order': u'3',
'uri': 'executive-committee'},
{'name': 'FINANCIAL INFO',
'order': u'4',
'uri': 'financial-info'},
{'name': 'SPONSORS AND AFFILIATIONS',
'order': u'5',
'uri': 'sponsors-and-affiliations'},
{'name': 'ABOUT', 'order': u'1', 'uri': 'about'}]}
尝试使用此代码,但我收到了错误
sorted(sub_links, key=lambda x: sub_links[x]['order'])
TypeError:列表索引必须是整数,而不是str
任何提示?
答案 0 :(得分:2)
您无法对字典本身进行排序。 python中的字典没有订单。
key
函数。 sub_links[x]
=> sub_links['about-us']
; sub_links[x]['order']
失败,因为sub_links[x]
会返回一个列表。您可以对字典中的列表进行排序:d['about-us']
还应更改sorted
函数的用法:sorted
将每个项目传递给键函数,而不是项目的索引。
>>> sorted(d['about-us'], key=lambda x: int(x['order']))
[{'uri': 'about', 'name': 'ABOUT', 'order': u'1'},
{'uri': 'constitution', 'name': 'CONSTITUTION', 'order': u'2'},
{'uri': 'executive-committee', 'name': 'EXECUTIVE COMMITTEE', 'order': u'3'},
{'uri': 'financial-info', 'name': 'FINANCIAL INFO', 'order': u'4'},
{'uri': 'sponsors-and-affiliations', 'name': 'SPONSORS AND AFFILIATIONS', 'order': u'5'}]
如果您需要对所有字典值进行排序,请循环显示值。
for value in d.values(): # use `itervalues` In Python 2.x
value.sort(key=lambda x: int(x['order']))
答案 1 :(得分:0)
key
lambda函数在调用时接收字典的键作为其参数x
- 在这种情况下,当对字典中的唯一键执行时,调用看起来像这样:< / p>
# this is JUST for demonstrating the execution of the code--this is not actual Python code
lambda("about-us"):
return sub_links["about-us"]["order"]
执行此操作时,sub_links["about-us"]
将返回该键的值,即列表。当语句的下一部分执行(<the list that got returned>["order"]
)时,TypeError
会被抛出,因为列表需要整数索引。
这里有一个更大的问题 - 似乎你在整个字典上调用sorted
,它只包含1个值。仅对一个条目进行排序是没有意义的,它不应该被用来排序你想要排序的内容,这是字典的内部列表。
如果你想对字典的内部列表(“about-us”键的相应字典值)进行排序,你需要这样的东西(如同建议的那样):
sorted(sub_links["about-us"], key=lambda d: int(d["order"]))