【发布时间】:2019-08-01 19:44:38
【问题描述】:
我在尝试根据匹配字符串的值对字典列表进行排序时遇到问题。这是一个例子:
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"}]
任何帮助将不胜感激。谢谢!
【问题讨论】:
-
test.sort(key=lambda x: x['password'] != 'test3') -
所以
d['password'] == 'test3'的字典必须排在第一位,其余的字典可以任意顺序排列? -
@chepner 是的
-
@StardustGogeta 有效!谢谢!
-
不是真正的重复,因为我们是根据值派生的值排序的,而不是值本身。 (不过,可能会有更好的副本。)
标签: python list sorting dictionary