I am new to Python and I am trying to insert values into specific dictionary keys in a list. However, they all share the same key name and when I try to insert a value, all the keys with the same name in the different dictionaries are also updated.
Here's a simple example of what I am using:
name = "Jacob`Mary`Anne"
age = "20`34`31"
text = "Text1`Text2`Text3"
def compile():
dict = {"name": "", "age": "", "text": ""}
full_dict = []
for i in range(3):
full_dict.append(dict)
return {
"date": "",
"content": [full_dict]
}
response = compile()
name_split = name.split('`')
age_split = age.split('`')
text_split = text.split('`')
for i in range(3):
response[content][0][i]['name'] = name_split[i]
response[content][0][i]['age'] = age_split[i]
response[content][0][i]['text'] = text_split[i]
I am trying to get an output that looks like this:
[[{'name':'Jacob', 'age':'20', 'text':'Text1'}, {'name':'Mary', 'age':'34', 'text':'Text2'}, {'name':'Anne', 'age':'31', 'text':'Text3'}]]
However, I end up with an output like this:
[[{'name':'Anne', 'age':'31', 'text':'Text3'}, {'name':'Anne', 'age':'31', 'text':'Text3'}, {'name':'Anne', 'age':'31', 'text':'Text3'}]]
I'd appreciate any help I can get. Thanks!
CodePudding user response:
There are some things going on here. But first, let me show you why your code behaves the way it does.
You are actually adding the same object to the list in you compile
-Function.
This means that your dict
-variable is pointing to the same memory-adress, therefore this memory-address will be called when accessing the full_dict
-list on any position. The short solution is to add a copy of dict
.
Change full_dict.append(dict)
to full_dict.append(dict.copy())
and it will work as intended.
One word of caution though:
You should not overwrite keywords which are used by python. dict
is a keyword for creating a default dictionary and can be used as some_dict_name = dict()
.
In general it is also good practice to not mix up the variables names with different structures as list and dictionaries. You have a variable name full_dict
which is in fact a list. This is confusing because one would expect a dictionary at first.
Small note: I think you got confused at the end by and you meant to write
response[content][0][i]['name'] = split_name[i]
response[content][0][i]['age'] = split_age[i]
response[content][0][i]['text'] = split_text[i]
instead of
response[content][0][i]['name'] = name[i]
response[content][0][i]['age'] = age[i]
response[content][0][i]['text'] = text[i]
CodePudding user response:
Your problem is in function compile() You are appending 3 times the same dictionary to the list full_dict (which is btw. a little confusion name)
def compile():
full_dict = []
for i in range(3):
dict = {"name": "", "age": "", "text": ""}
full_dict.append(dict)
.
.
.
This should solve the problem, because it is creating a new dictionary in every loop