【问题标题】:Sorting a list of dictionaries based on a value根据值对字典列表进行排序
【发布时间】: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


【解决方案1】:
test.sort(key=lambda x: x['password'] != 'test3')

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    相关资源
    最近更新 更多