我如何按以元组为值的值对字典进行排序
How do i sort a dictionary by value that has tuples as values
我有一个以字符串作为键和以两个元素作为值的元组的字典:
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)}
知道如何实现吗?
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))]
我有一个以字符串作为键和以两个元素作为值的元组的字典:
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)}
知道如何实现吗?
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))]