Dictionary sorting based on the Value of lists in the value
本问题已经有最佳答案,请猛点这里访问。
我有一本字典
1 | my_dict = {'name':['a','b','c','d','e'],'c1':[0,0,1,2,0],'c2':[3,0,2,1,2],'c3':[1,2,3,4,5]} |
我想根据
我已尝试以下操作,但出现错误:
1 2 3 4 5 | c1_list = count_dict.get('c1') c1_list.sort(reverse=True) index_map = {v: i for i, v in enumerate(c1_list)} print sorted(my_dict.items(), key=lambda pair: index_map[pair[0]]) |
预期输出:
1 | {'name':['d','c','a','e','b'],'c1':[2,1,0,0,0],'c2':[1,2,3,2,0],'c3':[4,3,1,5,2]} |
如果要按特定的相反顺序对所有值进行排序,这里是
Python3
1 2 3 4 5 6 7 | my_dict = my_dict = {'name':['a','b','c','d','e'],'c1':[0,0,1,2,0],'c2':[3,0,2,1,2],'c3':[1,2,3,4,5]} sort_by = [my_dict['c1'], my_dict['c2']] for k, v in my_dict.items(): my_dict[k] = [i for *_, i in sorted(zip(*sort_by, v), key=lambda x: x[:-1], reverse=True)] print(my_dict) |
输出:
1 | {'name': ['d', 'c', 'a', 'e', 'b'], 'c1': [2, 1, 0, 0, 0], 'c2': [1, 2, 3, 2, 0], 'c3': [4, 3, 1, 5, 2]} |
号
Python2
1 2 3 4 5 6 7 | my_dict = my_dict = {'name':['a','b','c','d','e'],'c1':[0,0,1,2,0],'c2':[3,0,2,1,2],'c3':[1,2,3,4,5]} sort_by = [my_dict['c1'], my_dict['c2']] for k, v in my_dict.items(): my_dict[k] = [i[0] for i in sorted(zip(v, *sort_by), key=lambda x: x[1:], reverse=True)] print(my_dict) |
输出:
1 | {'name': ['d', 'c', 'a', 'e', 'b'], 'c1': [2, 1, 0, 0, 0], 'c2': [1, 2, 3, 2, 0], 'c3': [4, 3, 1, 5, 2]} |
号
熊猫
通常我会使用
1 2 3 4 5 6 7 | import pandas as pd my_dict = {'name':['a','b','c','d','e'],'c1':[0,0,1,2,0],'c2':[3,0,2,1,2],'c3':[1,2,3,4,5]} df = pd.DataFrame(my_dict) df_sorted = df.sort_values(by=['c1', 'c2'])[::-1] sorted_dict = df_sorted.to_dict('list') |
输出:
1 | {'name': ['d', 'c', 'a', 'e', 'b'], 'c1': [2, 1, 0, 0, 0], 'c2': [1, 2, 3, 2, 0], 'c3': [4, 3, 1, 5, 2]} |
。