Why dictionary values aren't in the inserted order?

前端 未结 6 858
野的像风
野的像风 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 02:44

    Clearly you know about lists. You can ask for the element at the ith index of a list. 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

提交回复
热议问题