Why are Python dictionaries NOT stored in the order they were created? [duplicate]

2024/7/8 6:26:01

Just curious more than anything else, but why isn't a dictionary such as the one below not ordered the same as it was created? But when I print out test it returns the same order from then on...

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

It's not that I need them ordered, but it's just been on my mind for awhile as to what is occurring here.

The only thing I've found on this is a quote from this article:

Python uses complex algorithms to determine where the key-value pairs are stored in a dictionary.

But what are these "complex algorithms" and why?

Answer

Python needs to be able to access D[thing] quickly.

If it stores the values in the order that it receives them, then when you ask it for D[thing], it doesn't know in advance where it put that value. It has to go and find where the key thing appears and then find that value. Since it has no control over the order these are received, this would take about N/2 steps on average where N is the number of keys it's received.

But if instead it has a function (called a hash) that can turn thing in to a location in memory, it can quickly take thing and calculate that value, and check in that spot of memory. Of course, it's got to do a bit more overhead - checking that D[thing] has actually been defined, and checking for those rare cases where you may have defined D[thing1] and D[thing2] where the hash function of thing1 and thing2 happen to be the same (in which case a "collision" occurs and python has to figure out a new place to put one of them).


So for your example, you might expect that when you search for test['four'] it just goes to the last entry in a list it's stored and says "aha, that's '4'." But it can't just do that. How does it know that four corresponds to the last entry of the list. It could have come in any order, so it would have to create some other data structure which allows it to quickly tell that four was the last entry. This would take a lot of overhead.

It would be possible to make it output things in the order they were entered, but that would still require additional overhead tracking the order things were entered.

https://en.xdnf.cn/q/120409.html

Related Q&A

How to extract out a non-continuous matrix from a larger matrix based on a list [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 2…

Python get info from long complicated string

Im trying to get info from strings that I have parsed. Im trying to get the font size. This is the string Im returning style="fill: rgb(0, 0, 0); fill-opacity: 1; font-family: ProjectStocksFont; f…

How can i ask for user input and use that input for this text summarizer i created? [duplicate]

This question already has answers here:How do I read from stdin?(25 answers)Closed last year.I have created a text summarizer based on a code I found on Github. Im trying to have to script ask for the…

Return to main menu function for python calculator program

I was asked to write a calculator in Python, and I completed it, but there is only one issue that needs to be fixed. What is the prerequisite? "Once the user inputs/selects an arithmetic operatio…

what the code to use in # Complete this function with recursion in lines 4

# TODO: 2. Create a function that counts the sum of all the numbers in a list belownumber = [1,2,3,4,5] # Use this list as inputdef hitung_total(listKu):# Complete this function with recursionreturn li…

Pip cannot install some Python packages due to missing platform tag in M1 Mac

Lately I have been facing issues installing packages through pip. For e.g. when I try to install the torch package, it fails with the below error > arch arm64 > python --version 3.10.12 ❯ pip --…

find (i,j) location of closest (long,lat) values in a 2D array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 9…

an error occured to add picture in python

I am new in python and I am using python 3.5 version. I want to add photo to python, and heres the code I wrote:from tkinter import * win=Tk() win.title("Python Image")canvas=Canvas(win,width…

Implementing stack in python by using lists as stacks [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

Addition function in Python is not working as expected

I tried to create a function using which I want to do mathematical operations like (Addition and Multiplication), I could able to prompt the values and when I insert the values result is not returning …