按值的长度对字典排序 [英] Sort a dictionary by length of the value
本文介绍了按值的长度对字典排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有字典:
d = {'a':[1,3], 'b':[3,4,5,6], 'c':[1], 'd':[1,2,3] }
我想用前两个key:value对制作一个较小的新字典,按值列表中的len
排序.因此,在这种情况下,我想要:
I want to make a smaller, new dictionary with the top two key:value pairs, sorted by the len
of the lists in value. So in this case, I want:
newd = {'b':[3,4,5,6], 'd':[1,2,3] }
我尝试了此答案,但出现了以下错误:>
I tried this answer but got this error:
NameError: global name 'd' is not defined
推荐答案
一种方法是根据值的长度对项目进行排序,然后从最后两个项目创建字典.
One approach is to sort the items according to length of value, and then create a dictionary from the last two items.
sorted_items = sorted(d.items(), key = lambda item : len(item[1]))
newd = dict(sorted_items[-2:])
这篇关于按值的长度对字典排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文