如何按值将元组作为值对字典进行排序

时间:2015-03-12 13:43:36

标签: python python-2.7 sorting dictionary tuples

我有一个字典,其中包含字符串作为键和元组,其中包含两个元素值:

d = {"Alex": (18, 22), "Maria": (5, 11), "John": (18, 19), "Jim": (5, 8)}

我正在尝试按值对字典进行排序,但我希望降序为value[0],升序为value[1]

当我使用时:

sorted_dict = sorted(d.items(), key=operator.itemgetter(1), reverse=True)

输出是:

{"Alex": (18, 22), "John": (18, 19), "Maria": (5, 11), "Jim": (5, 8)}

虽然我需要它:

{"John": (18, 19), "Alex": (18, 22), "Jim": (5, 8), "Maria": (5, 11)}

关于如何实现这一点的任何想法?

1 个答案:

答案 0 :(得分:1)

In [1]: sorted(a.items(), key=lambda e: (-e[1][0], +e[1][1]))
Out[1]: [('John', (18, 19)), ('Alex', (18, 22)), ('Jim', (5, 8)), ('Maria', (5, 11))]