繁体   English   中英

使用python更新字典值

[英]Update a dictionary value using python

我有一个json文件,当使用json.loads()在python中加载该文件时,它会成为一个dictionary JSON数据是一个nested dictionary可以包含一个'groups'内的另一个关键'groups'键。 'groups'键中的值是'name'键和'properties'键。

每个'properties'键都有一个唯一的'name''value'键。

我的目标是搜索'name'键值为"SportCar"'groups'键,其'name' properties键的name键值为"BMW" ,只有在满足这些条件时,才更新'data'键,从'data':value1'data':value2

json的示例如下

{
  "groups": [
    {
      "name": "SportCar",
      "properties": [
        {
          "name": "BMW",
          "value": {
            "type": "String",
            "encoding": "utf-8",
            "data": "value1"
          }
        },
        {
          "name": "Audi",
          "value": {
            "type": "Boolean",
            "data": true
          }
        }
      ],
      "groups": [
        {
          "name": "Trucks",
          "properties": [
            {
              "name": "Volvo",
              "value": {
                "type": "String",
                "encoding": "utf-8",
                "data": "value1"
              }
            }
          ]
        }
      ]
    },
    {
      "name": "MotorCycle",
      "properties": [
        {
          "name": "Yamaha",
          "value": {
            "type": "String",
            "encoding": "utf-8",
            "data": "value1"
          }
        }
      ],
      "groups": [
        {
          "name": "Speeders",
          "properties": [
            {
              "name": "prop2",
              "value": {
                "type": "String",
                "encoding": "utf-8",
                "data": "value1"
              }
            }
          ]
        }
      ]
    }
  ]
}

上面的json包含在myjson22.json中。 到目前为止,这是我尝试过的:

import json
from pprint import pprint

json_data=open('myjson22.json', 'r')
data = json.load(json_data)
#print(data)

def get_recursively(search_dict, field):
    """
    To read the json data as type dict and search all 'groups' keys for the 'name' key value value provided.
    """
    fields_found = []

    for key, value in search_dict.items():

        if key == field:
            fields_found.append(value)

        elif isinstance(value, dict):
            results = get_recursively(value, field)
            for result in results:
                fields_found.append(result)

        elif isinstance(value, list):
            for item in value:
                if isinstance(item, dict):
                    more_results = get_recursively(item, field)
                    for another_result in more_results:
                        fields_found.append(another_result)

    return fields_found
get_recursively(data, ["properties"][0])

输出为:

 [[{'name': 'BMW',
   'value': {'data': 'value1', 'encoding': 'utf-8', 'type': 'String'}},
  {'name': 'Audi', 'value': {'data': True, 'type': 'Boolean'}}],
 [{'name': 'Volvo',
   'value': {'data': 'value1', 'encoding': 'utf-8', 'type': 'String'}}],
 [{'name': 'Yamaha',
   'value': {'data': 'value1', 'encoding': 'utf-8', 'type': 'String'}}],
 [{'name': 'prop2',
   'value': {'data': 'value1', 'encoding': 'utf-8', 'type': 'String'}}]]

回溯是实现此递归解决方案的一种方法。 如果没有发现嵌套在根键中的'groups'键,则'name'键值与groups_name参数匹配,在本例中为“ SportCar”。 如果满足此条件,请检查同一'groups'键(即“ SportCar”键), 'properties'键中的值,并将其'name'键值与properties_name参数(在本例中为“ BMW”)相匹配。 如果第二个条件也成立,则根据要求更新相同'properties'键中的'data'键值,否则返回(用于回溯)。

import json

json_data = open('myjson22.json', 'r')

data = json.load(json_data)

def get_recursively( myJson, groups_name, properties_name, value2):

    if 'groups' in myJson.keys():
        # As there are multiple values inside 'groups' key
        for jsonInsideGroupsKey in myJson['groups']:  
            get_recursively( jsonInsideGroupsKey, groups_name, properties_name, value2)

    if 'name' in myJson.keys():
        # check for groups name
        if myJson['name'] == groups_name:
            # check for properties name
            if myJson['properties'][0]['name'] == properties_name:
                # Update value. The changes will persist as we backtrack because
                # we are making the update at the original memory location
                # and not on a copy. For more info see deep and shallow copy.
                myJson['properties'][0]['value']['data'] = value2
    return

get_recursively(data,'SportCar','BMW','changedValue1')
get_recursively(data,'Speeders','prop2','changedValue2')
print data

我的输出:

{u'groups':[{u'name':u'SportCar',u'groups':[{u'name':u'Trucks',u'properties':[{u'name':u'Volvo ',u'value':{u'data':u'value1',u'type':u'String',u'encoding':u'utf-8'}}}}],u'properties': [{u'name':u'BMW',u'value':{u'data': 'changedValue1' ,u'type':u'String',u'encoding':u'utf-8'}} ,{u'name':u'Audi',u'value':{u'data':True,u'type':u'Boolean'}}]},{u'name':u'MotorCycle', u'groups':[{u'name':u'Speeders',u'properties':[{u'name':u'prop2',u'value':{u'data': 'changedValue2' ,u 'type':u'String',u'encoding':u'utf-8'}}}}],u'properties':[{u'name':u'Yamaha',u'value':{u '数据':u'value1',u'类型':u'String',u'encoding':u'utf-8'}}}}]}

美化为:

{
  "groups": [
    {
      "name": "SportCar",
      "properties": [
    {
      "name": "BMW",
      "value": {
        "type": "String",
        "encoding": "utf-8",
        "data": "ChangedValue1"
      }
    },
    {
      "name": "Audi",
      "value": {
        "type": "Boolean",
        "data": true
      }
    }
      ],
      "groups": [
    {
      "name": "Trucks",
      "properties": [
        {
          "name": "Volvo",
          "value": {
            "type": "String",
            "encoding": "utf-8",
            "data": "value1"
          }
        }
      ]
    }
      ]
    },
    {
      "name": "MotorCycle",
      "properties": [
    {
      "name": "Yamaha",
      "value": {
        "type": "String",
        "encoding": "utf-8",
        "data": "value1"
      }
    }
      ],
      "groups": [
    {
      "name": "Speeders",
      "properties": [
        {
          "name": "prop2",
          "value": {
            "type": "String",
            "encoding": "utf-8",
            "data": "ChangedValue2"
          }
        }
      ]
    }
      ]
    }
  ]
}

暂无
暂无

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

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