如何根据键(元组)的第二个元素对字典进行排序

Hri*_*ngh 0 python lambda dictionary python-3.x

我有一个表格如下:-

table = {
        ('A', 10): 'student1',
        ('B', 12): 'student4', 
        ('C', 11): 'student3', 
        ('D', 11): 'student2',
        ('E', 9): 'student5'
        }
Run Code Online (Sandbox Code Playgroud)

我想按元组的第二项对该表进行排序(不需要就地)。

预期输出:-

table = {
        ('E', 9): 'student5'
        ('A', 10): 'student1',
        ('C', 11): 'student3', 
        ('D', 11): 'student2',
        ('B', 12): 'student4', 
        }
Run Code Online (Sandbox Code Playgroud)

rda*_*das 5

items()排序后从原始元组列表重新创建字典:

table = {
    ('A', 10): 'student1',
    ('B', 12): 'student4',
    ('C', 11): 'student3',
    ('D', 11): 'student2',
    ('E', 9): 'student5'
}
table = dict(sorted(table.items(), key=lambda x: x[0][1]))

print(table)
Run Code Online (Sandbox Code Playgroud)

结果:

{('E', 9): 'student5', ('A', 10): 'student1', ('C', 11): 'student3', ('D', 11): 'student2', ('B', 12): 'student4'}
Run Code Online (Sandbox Code Playgroud)