python - 在字典字典中对元组列表进行排序

时间:2018-05-09 00:02:05

标签: python list sorting dictionary tuples

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

{'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'))]}}

2 个答案:

答案 0 :(得分:4)

您可以使用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'))]}}

答案 1 :(得分:1)

您可以使用嵌套词典理解:

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'))]}}