python按值的长度排序字典

jwi*_*720 43 python sorting dictionary

我发现很多线程按照这里的值进行排序,但它似乎对我不起作用......

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

>>>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
Run Code Online (Sandbox Code Playgroud)

这可能吗?

jam*_*lak 79

>>> 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
Run Code Online (Sandbox Code Playgroud)

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

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

  • d是一个示例字典变量名称。在你的`dict`子里 (2认同)

小智 8

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': []}]
Run Code Online (Sandbox Code Playgroud)