根据值对字典列表进行排序

时间:2019-08-01 19:44:38

标签: python list sorting dictionary

我在尝试根据匹配字符串的值对字典列表进行排序时遇到麻烦。这是一个示例:

test = [{'username': "1", "password": "test1"},
        {"username": "3", "password": "test2"},
        {"username": "5", "password": "test3"}]

我想根据密码= test3对这本词典进行排序,因此它看起来像:

test = [{"username": "5", "password": "test3"},
        {'username': "1", "password": "test1"},
        {"username": "3", "password": "test2"}]

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:2)

test.sort(key=lambda x: x['password'] != 'test3')

列表的.sort()方法允许您使用任意的key函数。在这种情况下,如果False字段等于'password',我们将使用一个返回'test3'(等于0)的函数。