Reputation: 315
I'm using a dictionary in Python 2, and am wondering if the dictionary.values() returns a list of values in a particular order
i.e. the order they were given into the dictionary in?
Example
dict = {}
dict[1] = "potato"
dict[2] = "tomato"
dict[3] = "orange"
dict[4] = "carrot"
list_val = dict.values()
Is list_val in the order potato->tomato->orange->carrot
?
or is it in some other order?
This is a simple example, I mean will it return in the same order for even more complex structures?
For example, replace the strings with dictionaries making it a dictionary of dictionaries
NOTE: This was answered in the other thread, which is linked
Another good answer to refer to for conceptual answer is : This
Upvotes: 1
Views: 1198
Reputation: 15236
UPDATE:
After reading some documentation on hash tables (what dict in python use to store key
information) I found that the order in which you assign keys/values is not what defines its location in the has table. There is a really good video HERE that does a great job of explaining how a hash table works and what is going on during the key assignment to the hash table.
Basically a key is assigned a hash number that is then placed in the hash table according to its hash number rather than its key value. This hash number is placed first in the desired location on the hash table that corresponds with its hash number unless there is already something assigned to that location. If something else is already assigned to that location on the Hash Table then python does some calculations to chose the next best location. This can be before or after the desired location in the has table. HERE Is some documentation but I highly recommend watching the video I liked as it does a great job explaining this concept.
Upvotes: 2