代码之家  ›  专栏  ›  技术社区  ›  Qubix

按每个列表中的第二个元素对列表字典排序

  •  1
  • Qubix  · 技术社区  · 6 年前

    我有一本清单字典,例如:

    test_dict = { 'a' : [[1, 6, 8], [2, 5, 9], [54, 1, 34]],
                  'b' : [[1, 3, 8], [2, 1, 9], [54, 2, 34]],
                  'c' : [[1, 1, 8], [2, 9, 9], [54, 7, 34]]
                }
    

    我想按每个子列表中的第二个元素对每个值列表进行排序(升序)。所需的输出字典为:

    output_dict = { 'a' : [[54, 1, 34], [2, 5, 9], [1, 6, 8]],
                    'b' : [[2, 1, 9], [54, 2, 34], [1, 3, 8]],
                    'c' : [[1, 1, 8], [54, 7, 34], [2, 9, 9]]
                  }
    

    我在努力:

    sorted_dict = dict(sorted(test_dict.items(), key=lambda e: e[1][1]))
    sorted_dict.items()
    

    这似乎什么也做不了。

    2 回复  |  直到 6 年前
        1
  •  2
  •   jpp    6 年前

    您正在查找字典值中列表的排序, 不是字典键的顺序

    res = {k: sorted(v, key=lambda x: x[1]) for k, v in test_dict.items()}
    
    {'a': [[54, 1, 34], [2, 5, 9], [1, 6, 8]],
     'b': [[2, 1, 9], [54, 2, 34], [1, 3, 8]],
     'c': [[1, 1, 8], [54, 7, 34], [2, 9, 9]]}
    

    对于函数等价物,可以使用 key=operator.itemgetter(1) . 在Python3.6+中,应该保持字典顺序。在3.6之前,字典是无序的,您不应该期望任何特定的键顺序。

    要按键订购,您可以使用 collections.OrderedDict :

    from collections import OrderedDict
    
    res_ordered = OrderedDict(sorted(res.items(), key=lambda x: x[0]))
    
    OrderedDict([('a', [[54, 1, 34], [2, 5, 9], [1, 6, 8]]),
                 ('b', [[2, 1, 9], [54, 2, 34], [1, 3, 8]]),
                 ('c', [[1, 1, 8], [54, 7, 34], [2, 9, 9]])])
    
        2
  •  2
  •   ansu5555    6 年前

    你可以这样做,它将更新现有的字典

    test_dict = { 'a' : [[1, 6, 8], [2, 5, 9], [54, 1, 34]],
                  'b' : [[1, 3, 8], [2, 1, 9], [54, 2, 34]],
                  'c' : [[1, 1, 8], [2, 9, 9], [54, 7, 34]]
                }
    
    for k, v in test_dict.items():
        test_dict[k] = sorted(v, key=lambda e: e[1])
    
    print(test_dict)
    

    test_dict = { 'a' : [[1, 6, 8], [2, 5, 9], [54, 1, 34]],
                  'b' : [[1, 3, 8], [2, 1, 9], [54, 2, 34]],
                  'c' : [[1, 1, 8], [2, 9, 9], [54, 7, 34]]
                }
    
    new_dict = {k:sorted(v, key=lambda e: e[1]) for k, v in test_dict.items()}
    
    print(new_dict)