[英]How to sort a list of dictionaries in a dictionary and overwrite it in python
[英]How to sort list of dictionary of dictionaries?
我是 python 的新手,並且正在執行一項任務來實現 Lai Yang 全局快照算法。 我想訂購一個消息列表。 我根據用戶輸入制作了一個字典,但現在我想迭代每個進程並根據發送時間對消息進行排序。
我的字典結構是:
defaultdict(<class 'list'>,
{
1: [
{10: {'color': 'w', 'data': 4, 'receiver': 2, 'msgId': 'N3FAVSNZGQP0'}},
{1: {'color': 'w', 'data': 10, 'receiver': 2, 'msgId': '38BRJ7PPE42V'}}
]
2: [
{30: {'color': 'w', 'data': 50, 'receiver': 1, 'msgId': 'IY09Z5TH4D2G'}}
]
})
我希望它被排序為:
defaultdict(<class 'list'>,
{
1: [
{1: {'color': 'w', 'data': 10, 'receiver': 2, 'msgId': '38BRJ7PPE42V'}},
{10: {'color': 'w', 'data': 4, 'receiver': 2, 'msgId': 'N3FAVSNZGQP0'}}
]
2: [
{30: {'color': 'w', 'data': 50, 'receiver': 1, 'msgId': 'IY09Z5TH4D2G'}}
]
})
我用谷歌搜索了很多,瀏覽並嘗試了所有可能的解決方案。 我看到了 sortedcontainers 模塊,但即使這樣也給出了錯誤。 下面是我對 lambda 的最后一次嘗試,它也失敗了(TypeError: '<' not supported between 'dict' and 'dict')
for obj in sentMsgs:
msg = sorted(sentMsgs[obj], key=lambda x:list(x.values()))
sentMsgs[obj] = msgs
其他失敗的嘗試:
for obj in sentMsgs:
L = sentMsgs[obj]
msgs = [collections.OrderedDict((k, d[k](v)) for (k, v) in l.items()) for l in L]
msgs = collections.OrderedDict(sorted(sentMsgs[obj].items()))
sentMsgs[obj] = msgs
msgs = SortedDict(sentMsgs[obj])
sentMsgs[obj] = msgs
messages = {
1: [
{10: {'color': 'w', 'data': 4, 'receiver': 2, 'msgId': 'N3FAVSNZGQP0'}},
{1: {'color': 'w', 'data': 10, 'receiver': 2, 'msgId': '38BRJ7PPE42V'}}
],
2: [
{30: {'color': 'w', 'data': 50, 'receiver': 1, 'msgId': 'IY09Z5TH4D2G'}}
]
}
for message in messages:
messages[message].sort(key=lambda x: list(x.keys())[0])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.