【问题标题】:python - sort a list of tuple in a dictionary of dictionariespython - 对字典字典中的元组列表进行排序
【发布时间】:2018-10-19 00:04:42
【问题描述】:

我有一个字典,看起来像这样:

{'AAA': {'A1': [(0, ('a', 'b')), (3, ('c', 'd')), (2, ('a', 'b'))],
         'B1': [(3, ('a', 'b')), (2, ('a', 'b')), (1, ('c', 'd'))]},
 'BBB': {'A1': [(4, ('a', 'b')), (2, ('c', 'd')), (1, ('a', 'b'))],
         'B1': [(3, ('c', 'd')), (2, ('a', 'b')), (1, ('a', 'b'))]}}

我想按元组的元组列表中的第一个元素排序。

想要的结果:

{'AAA': {'A1': [(0, ('a', 'b')), (2, ('a', 'b')), (3, ('c', 'd'))],
         'B1': [(1, ('c', 'd')), (2, ('a', 'b')), (3, ('a', 'b'))]},
 'BBB': {'A1': [(1, ('a', 'b')), (2, ('c', 'd')), (4, ('a', 'b'))],
         'B1': [(1, ('a', 'b')), (2, ('a', 'b')), (3, ('c', 'd'))]}}

【问题讨论】:

    标签: python list sorting dictionary tuples


    【解决方案1】:

    您可以使用list.sort 方法对列表进行适当的排序

    d = {'AAA': {'A1': [(0, ('a', 'b')), (3, ('c', 'd')), (2, ('a', 'b'))],
                 'B1': [(3, ('a', 'b')), (2, ('a', 'b')), (1, ('c', 'd'))]},
         'BBB': {'A1': [(4, ('a', 'b')), (2, ('c', 'd')), (1, ('a', 'b'))],
                 'B1': [(3, ('c', 'd')), (2, ('a', 'b')), (1, ('a', 'b'))]}}
    
    for subd in d.values():
        for l in subd.values():
            l.sort()
    
    from pprint import pprint
    pprint(d)
    
    {'AAA': {'A1': [(0, ('a', 'b')), (2, ('a', 'b')), (3, ('c', 'd'))],
             'B1': [(1, ('c', 'd')), (2, ('a', 'b')), (3, ('a', 'b'))]},
     'BBB': {'A1': [(1, ('a', 'b')), (2, ('c', 'd')), (4, ('a', 'b'))],
             'B1': [(1, ('a', 'b')), (2, ('a', 'b')), (3, ('c', 'd'))]}}
    

    【讨论】:

      【解决方案2】:

      您可以使用嵌套字典推导:

      d = {'AAA': {'A1': [(0, ('a', 'b')), (2, ('a', 'b')), (3, ('c', 'd'))],
                   'B1': [(1, ('c', 'd')), (2, ('a', 'b')), (3, ('c', 'd'))]},
           'BBB': {'A1': [(1, ('a', 'b')), (2, ('c', 'd')), (4, ('a', 'b'))],
                   'B1': [(1, ('a', 'b')), (2, ('a', 'b')), (3, ('c', 'd'))]}}
      new_d = {a:{c:sorted(d, key=lambda x:x[0]) for c, d in b.items()} for a, b in d.items()}
      

      输出:

      {'AAA': {'A1': [(0, ('a', 'b')), (2, ('a', 'b')), (3, ('c', 'd'))],
               'B1': [(1, ('c', 'd')), (2, ('a', 'b')), (3, ('c', 'd'))]},
       'BBB': {'A1': [(1, ('a', 'b')), (2, ('c', 'd')), (4, ('a', 'b'))],
               'B1': [(1, ('a', 'b')), (2, ('a', 'b')), (3, ('c', 'd'))]}}
      

      【讨论】:

        猜你喜欢
        • 2016-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-13
        • 1970-01-01
        • 2018-10-24
        • 2023-04-05
        • 1970-01-01
        相关资源
        最近更新 更多