dictionary - Why are Python dictionaries NOT stored in the order they were created? -


this question has answer here:

just curious more else, why isn't dictionary such 1 below not ordered same created? when print out test returns same order on...

test = {'one':'1', 'two':'2', 'three':'3', 'four':'4'} 

it's not need them ordered, it's been on mind awhile occurring here.

the thing i've found on quote this article:

python uses complex algorithms determine key-value pairs stored in dictionary.

but these "complex algorithms" , why?

python needs able access d[thing] quickly.

if stores values in order receives them, when ask d[thing], doesn't know in advance put value. has go , find key thing appears , find value. since has no control on order these received, take n/2 steps on average n number of keys it's received.

but if instead has function (called hash) can turn thing in location in memory, can take thing , calculate value, , check in spot of memory. of course, it's got bit more overhead - checking d[thing] has been defined, , checking rare cases may have defined d[thing1] , d[thing2] hash function of thing1 , thing2 happen same (in case "collision" occurs , python has figure out new place put 1 of them).


so example, might expect when search test['four'] goes last entry in list it's stored , says "aha, that's '4'." can't that. how know four corresponds last entry of list. have come in order, have create other data structure allows tell four last entry. take lot of overhead.

it possible make output things in order entered, still require additional overhead tracking order things entered.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -