【问题标题】:sort a list of dictionary of dictionary in python在python中对字典列表进行排序
【发布时间】:2011-12-22 11:21:07
【问题描述】:

我只想在 python 中按 first_name 这个列表排序

list = [ { "profile" :  { "first_name" : "a", "last_name" : "b" } } ,
         { "profile" :  { "first_name" : "c", "last_name" : "d" } } ,
         { "profile" :  { "first_name" : "e", "last_name" : "f" } } ]

【问题讨论】:

  • 最好不要使用list作为变量名

标签: python list dictionary sorting


【解决方案1】:

要对列表本身进行排序,请使用:

lst.sort(key=lambda x: x['profile']['first_name'])

要保持lst 未排序并返回排序列表,请使用:

sorted(lst, key=lambda x: x['profile']['first_name'])

【讨论】:

  • @AtulMakwana - 你们很多人使用.sort() 语法而不是sorted()
【解决方案2】:

应该这样做:

>>> sorted(lst, key=lambda x: x['profile']['first_name'])

【讨论】:

    猜你喜欢
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    相关资源
    最近更新 更多