排序字典基于python中的字典值

时间:2017-08-24 23:07:45

标签: python sorting dictionary

我有这样的嵌套字典:

dic = {
    1:
    {
        'name': 'alice',
        'point': 10
    },
    2:
    {
        'name': 'john',
        'point': 12
    }
    3:
    {
        'name': 'mike',
        'point': 8
    }
    4:
    {
        'name' : 'rose',
        'point': 16
    }
    5:
    {
        'name': 'ben',
        'point': 5
    }
}

在我的情况下,我需要根据键'点'的值来对该词典进行降序排序。在第二级..所以结果将是这样的:

{
    4:
    {
        'name' : 'rose',
        'point': 16
    },
    2:
    {
        'name': 'john',
        'point': 12
    },
    1:
    {
        'name': 'alice',
        'point': 10
    },
    3:
    {
        'name': 'mike',
        'point': 8
    },
    5:
    {
        'name': 'ben',
        'point': 5
    }
}

有没有办法做到这一点?感谢..

2 个答案:

答案 0 :(得分:1)

正如其他人所提到的,在字典表格中你无法对这些项目进行排序。但是,这里有一个解决方案,可以根据您的需要工作,转换为键,值元组,然后按点排序(这是由您的输出隐含但未明确说明)。

d = {
    4:
    {
        'name' : 'rose',
        'point': 16
    },
    2:
    {
        'name': 'john',
        'point': 12
    },
    1:
    {
        'name': 'alice',
        'point': 10
    },
    3:
    {
        'name': 'mike',
        'point': 8
    },
    5:
    {
        'name': 'ben',
        'point': 5
    }
}

d_sorted = sorted(d.items(), key = lambda x: x[1]['point'],reverse=True)
print(d_sorted)

答案 1 :(得分:0)

不,你不能排序“那个词典”。字典是无序的。但是,您可以使用嵌套列表或其他人在评论中建议的内容。对于有序的词典,我建议您查看this

相关问题