如何保留python字典中项目的顺序? [英] How to preserve ordering of items in a python dictionary?

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

问题描述

我有一本这样的字典:

a = {'first': 1, 'second': 2, 'third': 3}

否,当我打印时,它以非常随机的顺序打印.而我需要它来始终保留订单.我该如何在python中进行此操作?

No when I print it prints in an very random order. Whereas I need it to preserve the order always. How can I go about doing this in python???

推荐答案

使用OrderedDict类.下面的示例.

Use OrderedDict class. Example below.

from collections import OrderedDict

dict=OrderedDict()
dict['first']=1
dict['second']=2
dict['third']=3
dict

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

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