SoFunction
Updated on 2024-11-21

Duplicate data when inserting a dictionary into a list in Python

Duplication of data when inserting a dictionary into a list

Let's start by posting the following code

UserInfo =[]
SelfMediaInfo = {'usr':'','pwd':'','videoIndex':''}
with open(r"D:\",'r') as SelfMediaFile:
    selfMediaInfos = ()
    for i in range(len(selfMediaInfos)):
        selfMediaInfo = selfMediaInfos[i].split('----')
        SelfMediaInfo['usr'] = selfMediaInfo[0].strip()
        SelfMediaInfo['pwd'] = selfMediaInfo[1].strip()
        SelfMediaInfo['videoIndex'] = selfMediaInfo[2].strip()
        (SelfMediaInfo)

The purpose of the code is to read the data in the txt document and then save it to usr, pwd, videoIndex according to the classification of the data.

According to the above code execution will find UserInfo in the list of all the data and selfMediaInfos in the last line of the data is exactly the same, with the original design of the code is contrary to the intention.

After debugging and analyzing, it was found that

As soon as the data in SelfMediaInfo changes, all the data in UserInfo changes with it.

Referring to the following articles here will solve the problem effectively

Problems encountered with storing dictionaries in Python lists

end up

(SelfMediaInfo)

modify to

(())

Problems are effectively addressed!

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.