What I want is to make a JSON that looks like this.
{
"filelist": [
{
"filename": "file1.txt",
"oof": 0
},
{
"filename": "file2.txt",
"oof": 0
},
{
"filename": "file3.txt",
"oof": 0
}
]
}
What I did was:
for line in listoflines:
mysmalldict ["filename"] = line.strip("\n")
mysmalldict ["oof"] = 0
dictcollector.append(mysmalldict)
mybigdict[filelist"] = dictcollector
print(json.dumps(mybigdict))
Unfortunately, What I got was:
{
"filelist": [
{
"filename": "file3.txt",
"oof": 0
},
{
"filename": "file3.txt",
"oof": 0
},
{
"filename": "file3.txt",
"oof": 0
}
]
}
Everything was overwritten by the last data.
After a couple of searches, I learned that Python dictionaries will overwrite data of the same keys. Some examples I found like this one doesn't fit my need as I need a duplicate key pair and not multiple values on one key.
I also found this one that is close but when I put the FakeDict on my dictcollector, it gives a different structure.
{
"filelist": [
'{
"filename": "file3.txt",
"oof": 0
}',
'{
"filename": "file3.txt",
"oof": 0
}',
'{
"filename": "file3.txt",
"oof": 0
}'
]
}
Is there a way to do this in Python? Or did I miss something?
dictcollector.append({"filename": line ...}).dictcollector.append(mysmalldict)This is your problem. You are not appending a copy of the dictionary as it exists in that moment -- you are appending the actual live dictionary object. (If it helps, you can think of this as a reference to the dictionary.) So when you update the dict with a new "filename" key in the next loop, you're also updating all the dicts that you previously appended to the list, because they are all the same object.