简体   繁体   English

更新python字典值并将结果写为json输出

[英]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:我有一段代码循环遍历 python 字典,获取所需的键/值并以 json 格式打印它们:

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将字典附加到列表中,然后将列表转储到 json 文件

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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