[英]How to sort a list of dictionaries in a dictionary and overwrite it in python
[英]python - sort a list of tuple in a dictionary of dictionaries
我有一本字典,看起來像這樣:
{'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'))]}}
您可以使用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'))]}}
您可以使用嵌套字典理解:
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'))]}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.