我正在尝试使用字典键以升序对列表进行排序。
您可以假设每个词典级别只有一个键。
输入:
res = [{'hi': {'abc': 5}}, {'bye': {'def': 5}}, {'hi': {'cba': 5}}]
我的代码:
def getitem (item):
return (item.keys())
print (sorted(res, key = getitem))
要求的输出:
[{'bye': {'def': 5}}, {'hi': {'abc': 5}}, {'hi': {'cba': 5}}]
您已经很接近了-只需将dict传递iter()
给它以创建一个迭代器,然后next()
在迭代器中请求该项目即可。如果有多个字典,则对字典的第一个键进行排序(Python 3.6+字典按插入时间排序)。比较器可以返回相对优先级的元组,如果外部键相等,则可以对内部键进行排序。
res = [{'hi': {'abc': 5}}, {'bye': {'def': 5}}, {'hi': {'cba': 5}}]
def compare(d):
outer = next(iter(d))
return outer, next(iter(d[outer]))
print(sorted(res, key=compare))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句