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?

21st Oct 2018, 8:23 AM
Pela Lala
Pela Lala - avatar
6 Antworten
+ 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.
21st Oct 2018, 10:58 AM
Anna
Anna - avatar
+ 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!
21st Oct 2018, 2:11 PM
Pela Lala
Pela Lala - avatar
+ 1
Note, Python 3.7 guarantees dictionary insertion order.
22nd Oct 2018, 5:53 PM
Kirk Schafer
Kirk Schafer - avatar
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
21st Oct 2018, 9:57 AM
Pela Lala
Pela Lala - avatar
0
After digging up, I found that the ‘hash table’ is the one behind the built-in indexer of the dictionary data type.
21st Oct 2018, 10:00 AM
Pela Lala
Pela Lala - avatar
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>)
23rd Oct 2018, 5:33 AM
Pela Lala
Pela Lala - avatar