skip to Main Content

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


  1. Chosen as BEST ANSWER

    Instead of appending the dict, just append it as a whole.

    Instead of

    dictcollector.append(mysmalldict)
    

    use

    dictcollector.append({"key":"pair","key":"pair"})
    

  2. You have to create a new dictionary on every iteration:

    for line in listoflines:
        mysmalldict = {} # add this
        mysmalldict["filename"] = line.strip("n")
        mysmalldict["oof"] = 0
        dictcollector.append(mysmalldict)
    
    mybigdict["filelist"] = dictcollector
    print(json.dumps(mybigdict))
    

    In your example, you have created mysmalldict outside the loop and assigned it 3 times to dictcollector.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search