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?
2
Answers
Instead of appending the dict, just append it as a whole.
Instead of
use
You have to create a new dictionary on every iteration:
In your example, you have created
mysmalldict
outside the loop and assigned it 3 times todictcollector
.