首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python更新字典值

使用python更新字典值
EN

Stack Overflow用户
提问于 2016-08-09 03:56:32
回答 1查看 4K关注 0票数 0

我有一个json文件,当使用json.loads()加载到python中时,它就变成了一个dictionary。json数据是一个nested dictionary,它可以在另一个'groups'密钥中包含一个'groups'密钥。'groups'密钥中的值是'name'密钥和'properties'密钥。

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

我的目标是搜索'groups'密钥,其'name'密钥的值为"SportCar",其properties密钥的name密钥的值为"BMW",并且仅当满足这些条件时,才将'data'密钥从'data':value1更新为'data':value2

下面是json的一个示例。

代码语言:javascript
复制
{
  "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中。这是我到目前为止尝试过的:

代码语言:javascript
复制
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])

输出结果是:

代码语言:javascript
复制
 [[{'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'}}]]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-09 06:11:54

实现这种递归解决方案的一种方法是回溯。当在根键中找不到嵌套的'groups'键时,'name'键值将与groups_name参数匹配,在本例中该参数为'SportCar‘。如果满足此条件,请检查相同'groups'键中的值(即'SportCar‘键) 'properties'键,并将其'name'键值与properties_name参数(在本例中为'BMW’)进行匹配。如果第二个条件也为真,则根据需要更新同一个'properties'键中的'data'键值,否则返回(用于回溯)。

代码语言:javascript
复制
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‘类型’:u‘字符串’,u‘编码’: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‘类型’:u‘字符串’,u‘编码’:u‘’utf 8‘}],u’‘properties’:{u‘’name‘:u’‘Yamaha’,u‘’value‘:{u’‘data’:u'value1',u‘’type‘:u’‘String’,u‘编码’:u‘’utf 8‘}

经过美化后,它看起来会像这样:

代码语言:javascript
复制
{
  "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"
          }
        }
      ]
    }
      ]
    }
  ]
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38837507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档