1.对字典进行排序:
d = {0: [2, 3], 1: [5, 4], 2: [9, 6], 3: [4, 7], 4: [8, 1], 5: [7, 2]}
1.1按键排序
print sorted(d.items(), lambda x, y: cmp(x[1][0], y[1][0]))
结果:
[(0, [2, 3]), (3, [4, 7]), (1, [5, 4]), (5, [7, 2]), (4, [8, 1]), (2, [9, 6])]
1.2按值元素排序(此处的值是一个list的第1个元素)
print sorted(d.items(), lambda x, y: cmp(x[1][1], y[1][1]))
结果:
[(4, [8, 1]), (5, [7, 2]), (0, [2, 3]), (1, [5, 4]), (2, [9, 6]), (3, [4, 7])]
注意:此处排序后生成的是tuple而不是dict对象。
1.3将列表转换为字典
dd = sorted(d.items(), lambda x, y: cmp(x[1][0], y[1][0]))
print dict(zip([x[0] for x in dd],[x[1] for x in dd]))
结果
{0: [2, 3], 1: [5, 4], 2: [9, 6], 3: [4, 7], 4: [8, 1], 5: [7, 2]}