【问题标题】:How to sort list of dictionary of dictionaries?如何对词典列表进行排序?
【发布时间】:2021-04-03 11:45:34
【问题描述】:

我是 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: '

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

【问题讨论】:

  • 你需要一个更好的抽象。如果这是一个练习,请继续。但在现实生活中,您应该问自己,一个对象是否比字典更有意义的抽象。我觉得水平太低了。为什么不是消息字典?
  • 这是一个消息字典。根索引表示 processId,并且在每个进程中是存储的 msgs 列表。关键是发送消息的时间,值包含该消息的元数据。
  • 按键排序就完成了。

标签: python list sorting dictionary


【解决方案1】:
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])

【讨论】:

    【解决方案2】:

    按每个列表的键对每个列表的字典进行排序:

    for a in sentMsgs.values():
        a.sort(key=list)
    

    Try it online!

    【讨论】:

      猜你喜欢
      • 2013-01-26
      • 1970-01-01
      • 2015-05-29
      • 1970-01-01
      • 2014-02-14
      • 1970-01-01
      • 2020-01-06
      • 1970-01-01
      相关资源
      最近更新 更多