关于python:如何按值对字典列表进行排序

How to sort a list of dictionaries of dictionaries by value

本问题已经有最佳答案,请猛点这里访问。

我有一个listdicts的dicts,如下:

1
mydic = [{'name':'a', 'loc':{'locname':'z'}, 'id':{'value':'1'}},{'name':'b', 'loc':{'locname':'o'}, 'id':{'value':'2'}}]

如何按locname排序?我应该得到这个:

1
mydic_sorted = [{'name':'b', 'loc':{'locname':'o'}, 'id':{'value':'2'}}, {'name':'a', 'loc':{'locname':'z'}, 'id':{'value':'1'}}]


可以使用lambda函数作为该函数的key参数。

1
2
3
>>> mydic = [{'name':'a', 'loc':{'locname':'z'}, 'id':{'value':'1'}},{'name':'b', 'loc':{'locname':'o'}, 'id':{'value':'2'}}]
>>> sorted(mydic,key = lambda x:x['loc']['locname'])
[{'loc': {'locname': 'o'}, 'name': 'b', 'id': {'value': '2'}}, {'loc': {'locname': 'z'}, 'name': 'a', 'id': {'value': '1'}}]

参考文献:文档

sorted(iterable[, cmp[, key[, reverse]]])

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).