变量更改时字典中的值更改

时间:2017-04-26 18:37:41

标签: python json dictionary

尝试从json文件中获取某些值,然后重新创建'一个新的json文件(有点像转换)。在下面的代码中。我做了以下事情:

  1. 定义返回字典的函数
  2. 对于json中的每个项目,如果函数返回结果,则将结果添加到位于parentObj词典内的列表
  3. oldFile.json:

    {
        "elements": [
            {
                "fieldValues": [
                    {
                    "id": "101",
                    "value": "John"
                    },
                    {
                    "id": "102",
                    "value": "Doe"
                    }
                ]
            },
            {
                "fieldValues": [
                    {
                    "id": "101",
                    "value": "Jane"
                    },
                    {
                    "id": "102",
                    "value": "Doe"
                    }
                ]
            }
        ]
    }
    

    file.py

    import json
    import os
    
    output = {}
    parentObj = {}
    parentObj['entries'] = []
    
    def grabVals(iCounter):
       # legend is a pre-determined dictionary matching ids with names (like first/last) 
       for myKey in subResults['elements'][iCounter]['fieldValues']:
            if myKey['id'] in legend:
                if 'value' in  myKey:
                    newEntry = {legend[myKey['id']]: myKey['value']}
                    output.update(newEntry) # first adds 'John', then 'Doe'
       # sample output below; next iteration would be 'Jane Doe'
       # {"First": "John", "Last": "Doe"}
       return output
    
    subResults = json.loads(oldFile.json)
    
    formCount = len(subResults['elements']) # subResults is the json above file. Grab total number of entries
    for counter in range(0, formCount):
        if convertTime(formEntryStamp, formEntryID) == 'keep':  # self defined function (returns keep or None)       
            parentObj['entries'].append(grabVals(counter))
        else:
            pass
    
    export = json.dumps(parent_obj, indent=4, sort_keys=False) # create new json based of dictionary
    
    f = open("finished.json", "w")
    f.write(export)
    f.close()
    

    finished.json

    中的预期数据
    {
        "entries": [
            {
                "First": "John",
                "Last": "Doe"
            },
            {
                "First": "Jane",
                "Last": "Doe"
            }
        ]
    }
    

    finished.json中的实际数据:

    {
        "entries": [
            {
                "First": "Jane",
                "Last": "Doe"
            },
            {
                "First": "Jane",
                "Last": "Doe"
            }
        ]
    }
    

    我的问题:如何永久写入parentObj?在函数中更改output时,parentObj内的值将被新值覆盖。这有可变的/可变对象吗?请告知我们需要进一步澄清。

    相关链接类似,但引用列表,而我是对象/词典:

1 个答案:

答案 0 :(得分:0)

在对python中的对象变异进行了一些阅读(链接here)之后,下面的代码解决了我的问题。与Juanpa在评论中所说的相似,我突变在我的函数中重用的变量(output)。我假设使用下面的代码,我正在创建一个副本,因此保持原始状态不变。

def grabVals(iCounter, output=None):
    if output == None:
        output = {}
        for myKey in subResults['elements'][iCounter]['fieldValues']:
            if myKey['id'] in legend:
                if 'value' in  myKey:
                    newEntry = {legend[myKey['id']]: myKey['value']}
                    output.update(newEntry)
    return output
相关问题