A
A
Alixperio2018-08-12 23:37:10
Python
Alixperio, 2018-08-12 23:37:10

We asked a problem about an infinitely nested dictionary in Python. Where to dig to give an answer?

The other day I dealt with the topic "Data passing by value and by reference" and I was given a task.
Gave 3 commands.
1. a = {'k':'v'}
2. a['z'] = a
3. a['z']['k'] = 1
Do them in order.
And they gave 3 questions:
1. What are we working with in line 2?
2. Why doesn't memory grow in line 2?
3. Why will it grow to 3?
I understood the answer to the first question - we are working with a reference data type.
I see that there is a recursion. Interestingly)
But the question of memory is not at all clear to me.
What should I watch or read to get the gist and be able to respond?
Thanks a lot!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2018-08-13
@Alixperio

If the wording of the problem was given to you exactly like this, then the person who asked it probably expected an answer that in the third paragraph in memory a place for the number 1 would be allocated, and in the second paragraph in the dictionary a link to the memory block already allocated in the first paragraph would simply be stored. But this is not entirely true. First, as Yuriy already wrote , memory for collections is allocated in blocks. Second, for each element of the dictionary, a PyDictEntry structure is created, storing the hash integer and two references to the PyObject structure representing the key and value of the element. This means that even storing a reference to an already existing object will consume 94 bytes (on a 64-bit platform).

R
Roman_V_M, 2018-08-14
@Roman_V_M

You can also remember that the integers 0-255 are created in advance and reused, i.e. in the 3rd line, a reference to an existing object representing the number 1 will be passed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question