2024-04-24 15:54:47 发布
网友
我有一个list的dicts的dicts如下:
list
dict
mydic = [{'name':'a', 'loc':{'locname':'z'}, 'id':{'value':'1'}},{'name':'b', 'loc':{'locname':'o'}, 'id':{'value':'2'}}]
如何按locname排序?我应该得到这个:
locname
可以使用lambda函数作为函数的key参数
lambda
key
>>> 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'}}]
参考:该docs
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).
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).
key=str.lower
None
可以使用
lambda
函数作为函数的key
参数参考:该docs
相关问题 更多 >
编程相关推荐