[英]sort list of dictionaries with sub-dictionaries and random key
help for sorting this list 帮助排序此列表
from operator import itemgetter
l = [
{'Ad28b4fac': {'url': 'http://a.com/', 'rating': 0}},
{'cx28b4ffc': {'url': 'http://www.dbr/', 'rating': 1}}
]
# sort this list by rating value
I try 我尝试
sorted(l, key=lambda x : l[x])
try 尝试
l.sort();
thanks for any help 谢谢你的帮助
Something like 就像是
>>> sorted(l, key=lambda x : list(x.keys())[0])
[{'Ad28b4fac': {'url': 'http://a.com/', 'rating': 0}}, {'cx28b4ffc': {'url': 'http://www.dbr/', 'rating': 1}}]
The parameter to the lambda for each iteration is the dictionaries in the list l
. 每次迭代的lambda参数是列表
l
的字典。 Now we wish to sort the data on the dictionary key. 现在我们希望对字典键上的数据进行排序。 So the
dict.keys()
function is used which will return all the keys in the dictionary. 因此,使用
dict.keys()
函数将返回字典中的所有键。 We take the first one [0]
which happens to be the only key and sort based on that. 我们采用第一个
[0]
,它恰好是唯一的键,并以此为基础进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.