如何按照插入的顺序从字典中检索项目? [英] How do you retrieve items from a dictionary in the order that they're inserted?

查看:126
本文介绍了如何按照插入的顺序从字典中检索项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以按照插入的顺序从Python字典中检索项目?

Is it possible to retrieve items from a Python dictionary in the order that they were inserted?

推荐答案

标准python dict 不能这样做。

The standard python dict isn't able to do this.

有一个提案( PEP 372 )将有序字典(跟踪插入顺序)添加到集合模块在标准库中。它包含各种的链接实现 订购 词典(另见这些 two 食谱)。

There is a proposal (PEP 372) to add an "ordered dictionary" (that keeps track of the order of insertion) to the collections module in the standard library. It includes links to various implementations of ordered dictionaries (see also these two recipes in the Python Cookbook).

如果你想要代码,你可能想坚持使用PEP中的参考实现与官方版本兼容(如果提案最终被接受)。

You might want to stick with the reference implementation in the PEP if you want your code to be compatible with the "official" version (if the proposal is eventually accepted).

编辑:PEP被接受并添加到p yth 2.7和3.1。请参阅文档

The PEP was accepted and added in python 2.7 and 3.1. See the docs.

这篇关于如何按照插入的顺序从字典中检索项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆