Why is the order not correct while I print the dictionary using For loop


This is the dictionary:
webster = {
"Aardvark" : "A star of a popular children's cartoon show.",
"Baa" : "The sound a goat makes.",
"Carpet": "Goes on the floor.",
"Dab": "A small amount."

while we print using for loop, it shows:
A star of a popular children's cartoon show.
Goes on the floor.
A small amount.
The sound a goat makes.


Hi courserunner80049 ,

I'm not sure what you mean exactly can you clarify more please ?


dict doesn't retain order


Unless we force it to, right?


No it isn't capable of retaining order - it's a hash table.

Another data structure exists that does both, but that'll have some trade-off, not sure what (collections.OrderedDict)


So in other words, don't try to force order on a dictionary. When order matters, revert to sorted list, or list in general?


Easiest to just consider it completely unordered, yes.

What you want from a data structure is a couple of simple promises, right.

The order of iteration of a Python dict has a whole bunch of if's and but's (I think you're guaranteed to get the same iteration order if you do the same operations in the same order in the same Python version number as long as nobody changed the seed for this order.. and this might only be true in CPython, but be different in Jython/IronPython/PyPy/others.. Just don't bother. It's extremely likely that there is something much more suitable, stick to those simple promises that the data structure is actually designed to meet, which for a dictionary is constant-time insertion/lookup/removal