Python 按上次更改值对 dict 进行排序

标签 python sorting dictionary

我正在为网站写信使。 所以,我有一些功能序列。
首先是

def get_messages(self):
    """select query"""
    messages = self.model.load(['or', ('sender', self.my_id), ('receiver', self.my_id)])
    return messages

返回数据库表中所有包含消息的记录,其中我是消息的发送者或接收者。
下一个函数是

def get_dialogs(self):
    """returns dialogs of curr user"""
    dialogs = {}
    for msg in self.messages:            
        if msg['receiver'] != self.my_id:
            tmp_d = msg['receiver']
        else:
            tmp_d = msg['sender']

        if tmp_d not in dialogs.keys():
            dialogs[tmp_d] = [msg]
        else:
            dialogs[tmp_d].append(msg)

    return dialogs

这里我正在准备字典,其中键是我与之交谈的用户。
问题是开始。
这是消息序列的屏幕截图。 enter image description here
我希望字典键序列按添加到值列表的最后一条消息排序。
在这里,我没有对它进行排序,实际上有一个问题(我无法理解的问题)- 默认的键序列应该是 1, 4, 222595, 99 但程序认为是 99, 1, 222595, 4(我检查了 get_messages 函数以正确的顺序返回消息。

主要问题
我如何根据上次更改的值对字典键进行排序(或者让知道字典无法排序的排序字典)

最佳答案

Python 中的

dict 未排序 - 键不以任何特定顺序出现。

考虑改用标准库中的 collections.OrderedDictOrderedDict 让您的项目按插入时间排序(即根据项目添加到字典的顺序)。

更新:如果您使用的是 Python 3.6+,dict 现在按插入顺序排序。这种行为在 Python 3.7+ 中得到保证(在 Python 3.6 中,这是真的,因为解释器是以这种方式构建的)。

关于Python 按上次更改值对 dict 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30047992/

相关文章:

python - 如何在 setup.py 中引导 numpy 安装

javascript - 函数内的排序脚本无法正常工作

c# - 如何在 C# 中的字典上实现 linq?

python - 在 Python 中聚合简单字典的最佳方法

python - APLpy错误: 'Colorbar' object has no attribute 'set_axis_label_text'

python - 在 Python 中基于地类网格求和土地面积网格

python , Selenium : 'Element is no longer attached to the DOM'

scala - 我怎么能省略这个 Nil Case

c# - 为什么 List<T>.Sort 方法重新排序等于 IComparable<T> 元素?

以列为字典的 Pandas 数据透视表