I have a question about adding, deleting, and modifying the Python Dictionary.

Asked 2 years ago, Updated 2 years ago, 61 views

When adding a new value to the python dictionary, Error 'dictionary changed size duration' occurs.

I selected the data in the table and put the value in search_dictionary (Type:dictionary). Value Type is a list. The key was placed as a unique key.

self.search_dict = {} (initialization)

key: 12ga 1010S// Value: [12ga 1010', 20191211105820', 'S']
key: 13ga 2020S// Value: ['13ga 2020', 20191211105820', 'S']
key: 44ga 2030S// Value: ['44ga 2030', 20191211105820', 'S']

As above, there is data in search_dict, and after proceeding in logic order, When new data is generated

list = "['55ga1234','20191211105822','S']" (insert new data)
self.search_dict['55ga1234S'] = list

You are about to add new data to search_dict as above. At this time, a 'dictionary changed size duration' error occurs

Obviously, if you insert the data in order as a test, it was added normally I don't understand why not.

The results of executing key and value as above for python test are as follows.

This is the part of the code where an additional error occurs.

python dictionary

2022-09-22 19:08

1 Answers

It's not the code that causes the error you mentioned in the question, so I'll just tell you what seems to be the problem.

>>> d = {}
>>> l = [1,2,3]
>>> d[1] = l
>>> d
{1: [1, 2, 3]}

>>> l[1] = 10
>>> d
{1: [1, 10, 3]}

>>> d[1] = l.copy()
>>> d
{1: [1, 10, 3]}
>>> 

If you specify the list l as the value of the dictionary, and then change the contents of l, the contents in the dictionary change as well. For this reason, I suspect that the list changes after putting data in the dictionary, resulting in results as if the data were not included.

To prevent this, in the example above, when specifying a value to a dictionary, the list was copied and specified.


2022-09-22 19:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.