How to sort a list of dictionaries of dictionaries by value
本问题已经有最佳答案,请猛点这里访问。
我有一个
1 | mydic = [{'name':'a', 'loc':{'locname':'z'}, 'id':{'value':'1'}},{'name':'b', 'loc':{'locname':'o'}, 'id':{'value':'2'}}] |
如何按
1 | mydic_sorted = [{'name':'b', 'loc':{'locname':'o'}, 'id':{'value':'2'}}, {'name':'a', 'loc':{'locname':'z'}, 'id':{'value':'1'}}] |
可以使用
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 isNone (compare the elements directly).