为什么字典值不在插入的顺序? [英] Why dictionary values aren't in the inserted order?
问题描述
当我宣布一个列表1,2,3,4,我做某事,即使打印我得到相同的序列1,2,3,4。
When i declare a list 1,2,3,4 and i do something with it , even just print i get back the same sequence 1,2,3,4.
但是,当我对字典做任何事情时,他们总是会改变数字序列,就像是用一种我无法理解的扭曲方式进行排序。
But when i do anything with dictionaries , they always change number sequence , like it is being sorted in a twisted way i can't understand .
test1 = [4,1,2,3,6,5]
print test1
test2 = {"c":3,"a":1,"b":2,"d":4}
print test2
[4, 1, 2, 3, 6, 5]
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
世界上如何a成为第一个元素和'c',即使按字母顺序排序字典,它应该是1,2,3,4或a,b,c,d不是1 ,3,2,4。 wT?F @!$!@ $#@!
How in the world did 'a' become the first element and 'c' , even if it alphabetically sorted the dictionary it should have been 1,2,3,4 or a,b,c,d not 1,3,2,4 . wT?F @!$!@$#@!
那么如何打印,从字典获取值而不改变元素的位置?
So how do i print , get values from dictionary without changing the positions of the elements .?
推荐答案
Python中的词典根据定义无序。如果您需要插入值的顺序(可在Python 2.7和3.x中使用),请使用 OrderedDict
。
Dictionaries in Python are unordered by definition. Use OrderedDict
if you need the order in which values were inserted (it's available in Python 2.7 and 3.x).
这篇关于为什么字典值不在插入的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!