创建字典时如何禁用自动排序

创建字典时如何禁用自动排序

本文介绍了python:创建字典时如何禁用自动排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,我需要帮助:

i need help for this case :

m={}
m[1]=1
m[333]=333
m[2]=2

# Result:
{1: 1, 2: 2, 333: 333}

因此,即使我最后一次没有输入'333',在打印出来时,我也会在字典的末尾列出该'333'.为什么这个字典"进行自动排序?以及如何禁用它?我可以创建一个功能来重新排序以修复订单.但这不是我想要的,我只是想打印并获得输出顺序,就像输入数据时的顺序一样.有什么好的解释和解决方案吗?

so even when i didn't enter '333' the last, i got this '333' listed in the end of the dictionary when print it out. why is this 'dictionary' doing auto sort? and how disable it? i can creata a function to re-sort to fix the order. but that's not what i want, i just simply want to print and get output order just like the order when i input the data. Is there any good explanation and is there any solution ?

推荐答案

它没有排序. dict根本没有排序,因此您不能以任何方式影响键的顺序.在2.7和3.1及更高版本中,有 collections.OrderedDict ,也有独立模块.

It is not sorting. dict is not ordered at all, so you cannot influence the key order in any way. There is collections.OrderedDict in 2.7 and 3.1+, there is also standalone module for 2.4-2.6.

这篇关于python:创建字典时如何禁用自动排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 04:55