简体   繁体   English

为什么字典值不在插入的顺序中?

[英]Why dictionary values aren't in the inserted order?

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. 当我声明一个列表1,2,3,4并且我对它做了一些事情,即使只是打印我也会得到相同的序列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}

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 . 世界上的'a'如何成为第一个元素和'c',即使按字母顺序对字典进行排序,它应该是1,2,3,4或a,b,c,d不是1,3,2, 4。 wT?F @!$!@$#@! wT?F @!$!@ $#@!

So how do i print , get values from dictionary without changing the positions of the elements .? 那么我如何打印,从字典中获取值而不改变元素的位置。

Dictionaries in Python are unordered by definition . Python中的字典按定义排序 Use OrderedDict if you need the order in which values were inserted (it's available in Python 2.7 and 3.x). 如果需要插入值的顺序(在Python 2.7和3.x中可用),请使用OrderedDict

dictionary sort order is undefined! 字典排序顺序未定义! Do not rely on it for anything. 不要依赖它。 Look for a sorted dictionary if you really want a sorted dictionary, but usually you don't need one. 如果你真的想要一个排序的字典,那就找一个排序的字典,但通常你不需要一个。

Examples: 例子:

  • python 2.7, it's built in to the collections module python 2.7,它内置于collections模块
  • Django has a SortedDict shipped with it Django附带了一个SortedDict
  • 2.4-2.7 you can use the ordereddict module, you can pip install or easy_install it 2.4-2.7你可以使用ordereddict模块,你可以pip install或easy_install它

Before you get so angry and frustrated, perhaps you should read about what a dictionary actually is and how it works: 在你变得如此愤怒和沮丧之前,也许你应该阅读一本字典究竟是什么以及它是如何工作的:

http://docs.python.org/library/stdtypes.html#mapping-types-dict http://docs.python.org/library/stdtypes.html#mapping-types-dict

Python dicts use a hash table as the underlying storage mechanism. Python dicts使用哈希表作为底层存储机制。 That means that a hash key is generated from the key that you provide. 这意味着从您提供的密钥生成散列密钥。 There are no guarantees about ordering with these hash keys. 无法保证使用这些哈希键进行排序。 The entries in a dictionary are fetched in sequential order of their location in the underlying hash table when you request values(), keys(), or items(). 当您请求values(),keys()或items()时,字典中的条目将按其在基础哈希表中的位置的顺序获取。

The advantage of using a hash table is that it is extremely fast. 使用哈希表的优点是它非常快。 Unlike the map class from c++ which uses a red-black tree storage mechanism ( which is sorted by the raw keys ), a hash table doesn't constantly need to be restructured to keep it efficient. 不像从C ++,它使用一个红-黑树存储机制(这由原始关键字排序)地图类,哈希表并不需要不断进行重组,以保持它有效的。 For more on hash tables, see: 有关哈希表的更多信息,请参阅:

http://en.wikipedia.org/wiki/Hash_table http://en.wikipedia.org/wiki/Hash_table

Like the other posters have said, look up OrderedDict if you need to have a key-sorted dictionary. 就像其他海报所说的那样,如果你需要一个按键排序的字典,请查看OrderedDict。

Good Luck! 祝好运!

Clearly you know about lists. 显然你知道列表。 You can ask for the element at the ith index of a list. 您可以在列表的第i个索引处请求元素。 This is because lists are ordered. 这是因为列表是有序的。

>>> [1,2,3,4] == [1,4,3,2]
False

In this context, you can think of dictionaries, but where the index is the key. 在这种情况下,您可以考虑字典,但索引是关键。 Therefore, two dictionaries are equal if the corresponding values of all keys in both dictionaries are the same (if one dictionary has keys that the other doesn't, then the two are not equal). 因此,如果两个字典中的所有键的对应值相同(如果一个字典具有另一个不具有的键,那么这两个不相等),则两个字典是相等的。 Thus: 从而:

>>> {1:'a', 2:'b'} == {2:'b', 1:'a'}
True

Further Trivia 进一步的琐事

A dictionary does something called hashing on the keys of the dictionary so that when you ask for the value at a particular key (index), it can retrieve this value faster. 字典在字典的键上执行称为散列的操作 ,这样当您在特定键(索引)处请求值时,它可以更快地检索此值。

Hope this helps 希望这可以帮助

Dictionaries are unsorted. 字典未分类。 This is well-documented. 这是有据可查的。 Do not rely on the ordering of dictionaries. 不要依赖词典的排序。

If you want to see the entries in order. 如果要按顺序查看条目。 something like: 就像是:

test2 = {"c":3,"a":1,"b":2,"d":4}
ks = test2.keys()
ks.sort()
for key in ks:
   print key + ':' + str(test2[key])

(cut,paste, season to taste) (切,粘,季节到味道)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM