[英]python - sort a list of tuple in a dictionary of dictionaries
I have a dictionary of dictionaries that looks something like this: 我有一本字典,看起来像这样:
{'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'))]}}
I want to order by the first element in the list of tuple of tuple. 我想按元组列表中的第一个元素排序。
Desired result: 所需结果:
{'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'))]}}
You can sort the lists in place using the list.sort
method 您可以使用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'))]}}
You can use a nested dictionary comprehension: 您可以使用嵌套字典理解:
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()}
Output: 输出:
{'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'))]}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.