简体   繁体   中英

update python dictionary values and write result as json output

I have a piece of code that loops through a python dictinary, graps the key/values needed and print them in a json format:

my original dictionary looks like this:

"mydict": [ 
         {
            "Name": "test", 
            "number": "18", 
            "entity": 0
        }, 
        {
            "Name": "update", 
            "number": "25", 
            "entity": 3
        }, 
        {
            "Name": "manage", 
            "number": "8", 
            "entity": 5
        }
]

Here is my code:

my_elements = resp.get('mydict')
final= {}
for item in my_elements :
    dic = {item.get('Name') : item.get('number'), 'entity' : item.get('entity')}
    output = json.dumps(dic, indent=4)
    print output

This is printing the expected output, however, when I try to write the output I get in a file I only get the last part of the answer and not the whole dictionary, this is what I get:

{
    "manage": 8,
    "entity": 5
}

while I want to get:

{
    "test": 18,
    "entity": 0
}
{
    "update": 25,
    "entity": 3
}
{
    "manage": 8,
    "entity": 5
}

This is the code I added hoping to get the needed output:

with open ('result.json','w') as outfile:
    json.dump(dic, outfile,)

But this returns the first output I do not desire. Thanks in advance for any help.

Append the dictionary to a list and then dump the list to a json file

Ex:

my_elements = resp.get('mydict')
final= []
for item in my_elements :
    final.append({item.get('Name') : item.get('number'), 'entity' : item.get('entity')})

with open ('result.json','w') as outfile:
    json.dump(final, outfile)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM