Why dictionary values aren't in the inserted order?

前端 未结 6 853
野的像风
野的像风 2020-12-19 02:37

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 alw

6条回答
  •  暖寄归人
    2020-12-19 03:03

    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

    Python dicts use a hash table as the underlying storage mechanism. 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().

    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. For more on hash tables, see:

    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.

    Good Luck!

提交回复
热议问题