[英]How to sort list of dictionary of dictionaries?
I am new to python and doing an assignment to implement Lai Yang Global Snapshot Algorithm.我是 python 的新手,并且正在执行一项任务来实现 Lai Yang 全局快照算法。 I want to order a list of messages.我想订购一个消息列表。 I made a dictionary based on user input, but now I want to iterate for each process and sort msgs based on the time they were sent.我根据用户输入制作了一个字典,但现在我想迭代每个进程并根据发送时间对消息进行排序。
My dictionary structure is:我的字典结构是:
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'}}
]
})
I want it to be sorted to:我希望它被排序为:
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'}}
]
})
I googled alot and browsed and tried all possible solutions.我用谷歌搜索了很多,浏览并尝试了所有可能的解决方案。 I saw sortedcontainers module but even that gave error.我看到了 sortedcontainers 模块,但即使这样也给出了错误。 Below is my last attempt of lambda, which is failing too (TypeError: '<' not supported between instances of 'dict' and 'dict')下面是我对 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
Other failed attempts:其他失败的尝试:
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])
Sorting each list's dicts by their key(s):按每个列表的键对每个列表的字典进行排序:
for a in sentMsgs.values():
a.sort(key=list)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.