I want to understand how works the memory allocation in python when adding new data to a dictionary. In the code below, I was waiting that every new added data was stacked at the end, however it does not happen.
repetitions = {}
for item in new_deltas:
list_aux = []
if float(item[1]) <= 30:
if float(item[0]) in repetitions:
aux = repetitions[float(item[0])]
aux.append(item[1])
repetitions[float(item[0])] = aux
else:
list_aux.append(item[1])
repetitions[float(item[0])] = list_aux
print(repetitions)
The results I got are as below. Thus, I would like to understand why the new appended data is not added at the end of the stack, it is added in the middle of it.
My input data is:
new_deltas = [[1.452, 3.292182683944702], [1.449, 4.7438647747039795], [1.494, 6.192960977554321], [1.429, 7.686920166015625]]
The print line outputs:
{1.452: [3.292182683944702]}
{1.452: [3.292182683944702], 1.449: [4.7438647747039795]}
{1.452: [3.292182683944702], 1.494: [6.192960977554321], 1.449: [4.7438647747039795]}
{1.429: [7.686920166015625], 1.452: [3.292182683944702], 1.494: [6.192960977554321], 1.449: [4.7438647747039795]}
Prior to Python 3.6, dictionaries were not ordered (see this stackoverflow thread for more on that). If you are using Python 3.6 or lower (in CPython 3.6 the fact that order is maintained is an implementation detail, but with Python 3.7 it became a language feature), you can use the OrderedDict to get the behavior you want.
For example, you could change the beginning of your code snippet to the following:
from collections import OrderedDict
repetitions = OrderedDict()
...