0
Is an object of the Python dictionary data type indexed in some way?
I thought that, in Python, the dictionary data type has index like what happens with the list data type. If not, a for-loop must be in used every time it does a query dict[key]. So, is an object of the Python dictionary data type indexed in some way?
6 Réponses
+ 5
A dictionary assigns a value to a key. I don't know why you would need an extra index to address the values because that's what the keys are for. Dictionaries are unordered, so even in a dictionary with only a couple of key-value pairs it would be a surprise what e.g. dictionary[0] would return.
Your code "proves" that dictionaries can't hold more than one value assigned to the same key. That's exactly the purpose of a dictionary.
+ 2
Thank you Anna! I have just figured it out myself.
Interesting! The proof-code was wrong. Because the declaration of the dict is actually a statement that did a modification-right-in-the-declaration.
Just do print(dict) to see what dict is after it was declared.
I appreciate you!
+ 1
Note, Python 3.7 guarantees dictionary insertion order.
0
I think the dictionary data type really have an built-in indexer, besides the keys made by user. This code is the proof:
https://code.sololearn.com/c9fio38NPGT7/?ref=app
0
After digging up, I found that the ‘hash table’ is the one behind the built-in indexer of the dictionary data type.
0
Thank you Kirk Schafer, so since Python 3.7, printing a dictionary object will list out its items in an order exactly the order they were inserted, unless we want to sort out the dictionary by using sorted(<dict_name>)