如何按键排序字典,其中键是元组

时间:2016-01-04 17:50:56

标签: python dictionary

我有一本字典

(x,y):z

我想按第二个值

对其进行排序

如果我有一个项目print sorted(d, key=lambda item:item[0][1]) ,我需要它基于y

我做了类似的事情,但它没有成功

@Html.DropDownListFor(x => x.CategoryId, new SelectList(Model.Categories, "Id", "Name"), "--Select--", new { @class = "form-control" })

任何想法?

2 个答案:

答案 0 :(得分:1)

差不多......

sorted(d,key=lambda x: x[1])
[('08', '10010'), ('23', '10017'), ('21', '10027'), ('06444', '10028')]

请注意,这是键的排序列表,而不是字典。要获取字典的完整视图(包含值),请将d更改为d.items()

答案 1 :(得分:1)

有两个问题:
1-要按键元组的第二个值排序,你忘记了.items()调用

>>> print sorted(d.items(), key=lambda item:item[0][1])
[(('08', '10010'), 6), (('23', '10017'), 6), (('21', '10027'), 6), (('06444', '10028'), 6)]

2-如果您需要一个按照该条件对键进行排序的dict,则需要一个OrderedDict对象,因为在默认情况下dict键的顺序不能保证

>>> print dict( sorted(d.items(), key=lambda item:item[0][1]))
{('23', '10017'): 6, ('21', '10027'): 6, ('08', '10010'): 6, ('06444', '10028'): 6}
>>> from collections import OrderedDict
>>> print OrderedDict( sorted(d.items(), key=lambda item:item[0][1]))
OrderedDict([(('08', '10010'), 6), (('23', '10017'), 6), (('21', '10027'), 6), (('06444', '10028'), 6)])