Python:字典中的元素顺序
以下是我的Django代码,它无法按预期工作:Python:字典中的元素顺序,python,django,Python,Django,以下是我的Django代码,它无法按预期工作: posts = Post.objects.all().order_by('-added')[:20] # ordered by 'added' post_list = dict([(obj.id, obj) for obj in posts]) # ... some operations with dictionary elements go here ... posts_to_return = [post for post_id, post
posts = Post.objects.all().order_by('-added')[:20] # ordered by 'added'
post_list = dict([(obj.id, obj) for obj in posts])
# ... some operations with dictionary elements go here ...
posts_to_return = [post for post_id, post in post_list.items()] # order by 'id' now!
有没有办法保持原始元素的顺序,以便通过posts\u to\u return
中的added
对帖子进行排序
谢谢大家!
编辑:Python 2.6、Django 1.3Python(以及大多数语言)中的dict没有顺序。你应该改为使用。这将保留项目添加时的顺序。如果加法的顺序不是您试图保留的顺序,您还可以查看
sorted()
内置的。您需要一个有序字典,据我所知,它将在Python3.3中提供。因此,您可能必须“手动”排序结果。根据您的操作(您没有显示),可能只需要重用原始的posts列表。但在不知道操作的情况下,我只能猜测 您可以使用命令而不是命令
from collections import OrderedDict
...
post_list = OrderedDict([(obj.id, obj) for obj in posts])
因为还没有人注意到这一点,所以我只需注意,文档表明这是等效的,可以在Python2.4及更高版本上使用。所以至少你不必自己动手 当您使用Django时,您可以使用
SortedDict
()使用SortedDict而不是dict(来自Django.utils.datastructures导入SortedDict
)
SortedDict在其keyOrder
属性中维护其顺序。因此,如果愿意,可以在不重构dict的情况下操纵排序。例如,要反转SortedAct的顺序,只需使用keyOrder.reverse()
还值得注意的是,您可以使用Python的许多字典实现中的一个来维护按排序顺序排列的键。这是至关重要的,如果你计划做任何插入到您的排序DICT。考虑这是纯Python和快速AS-C实现。有一个实现完全支持您所需的内容
>>> from sortedcontainers import SortedDict
>>> posts = Post.objects.all().order_by('-added')[:20] # ordered by 'added'
>>> post_list = SortedDict([(obj.id, obj) for obj in posts])
>>> # ... some operations with dictionary elements go here ...
>>> # This is now automatically ordered by id:
>>> posts_to_return = [post for post_id, post in post_list.items()]
还有一种方法可以将几个流行的选项相互比较。Django的意思是,我必须坚持使用python 2。x@SilverLight:您看到了“see Other”位,并使用了一个配方?@Silverlight:OrderedDict是Python 2.7xThank中标准库的一部分!arie的速度更快,但因为这个例子,我接受了你的答案。
>>> from sortedcontainers import SortedDict
>>> posts = Post.objects.all().order_by('-added')[:20] # ordered by 'added'
>>> post_list = SortedDict([(obj.id, obj) for obj in posts])
>>> # ... some operations with dictionary elements go here ...
>>> # This is now automatically ordered by id:
>>> posts_to_return = [post for post_id, post in post_list.items()]