python按值的长度排序字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16868457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:53:03  来源:igfitidea点击:

python sorting dictionary by length of values

pythonsortingdictionary

提问by jwillis0720

I have found many threads for sorting by values like herebut it doesn't seem to be working for me...

我发现很多线程可以像这里这样按值排序,但它似乎对我不起作用......

I have a dictionary of lists that have tuples. Each list has a different amount of tuples. I want to sort the dictionary by how many tuples each list contain.

我有一个包含元组的列表字典。每个列表都有不同数量的元组。我想按每个列表包含多少元组对字典进行排序。

>>>to_format 
>>>{"one":[(1,3),(1,4)],"two":[(1,2),(1,2),(1,3)],"three":[(1,1)]}
>>>for key in some_sort(to_format):
       print key,
>>>two one three

Is this possible?

这可能吗?

采纳答案by jamylak

>>> d = {"one": [(1,3),(1,4)], "two": [(1,2),(1,2),(1,3)], "three": [(1,1)]}
>>> for k in sorted(d, key=lambda k: len(d[k]), reverse=True):
        print k,


two one three

Here is a universal solution that works on Python 2 & Python 3:

这是适用于 Python 2 和 Python 3 的通用解决方案:

>>> print(' '.join(sorted(d, key=lambda k: len(d[k]), reverse=True)))
two one three

回答by Oleksiy Tsebriy

dict= {'a': [9,2,3,4,5], 'b': [1,2,3,4, 5, 6], 'c': [], 'd': [1,2,3,4], 'e': [1,2]}
dict_temp = {'a': 'hello', 'b': 'bye', 'c': '', 'd': 'aa', 'e': 'zz'}

def sort_by_values_len(dict):
    dict_len= {key: len(value) for key, value in dict.items()}
    import operator
    sorted_key_list = sorted(dict_len.items(), key=operator.itemgetter(1), reverse=True)
    sorted_dict = [{item[0]: dict[item [0]]} for item in sorted_key_list]
    return sorted_dict

print (sort_by_values_len(dict))

output:
[{'b': [1, 2, 3, 4, 5, 6]}, {'a': [9, 2, 3, 4, 5]}, {'d': [1, 2, 3, 4]}, {'e': [1, 2]}, {'c': []}]