模式中的Python字典

时间:2019-03-20 12:01:03

标签: python dictionary

我需要检查模式文件中声明的所有键是否都存在于字典中,如果不存在,则需要使用给定类型的默认值填充它们。我需要动态地执行此操作,因为结构可能比下面的结构还要复杂。

 {
  "type": "object",
  "properties": {
    "vid": {
      "type": ["null", "integer"]
    },
    "merged-vids": {
      "type": ["null", "array"],
      "items": {
        "type": ["null", "integer"]
      }
    },
    "portal-id": {
      "type": ["null", "integer"]
    },
    "is-contact": {
      "type": ["null", "boolean"]
    }
    "form-submissions": {
      "type": ["null", "array"],
      "items": {
        "type": ["null", "object"],
        "properties": {
          "conversion-id": {
            "type": ["null", "string"]
          },
          "timestamp": {
            "type": ["null", "string"],
            "format": "date-time"
          },
          "form-id": {
            "type": ["null", "string"]
          },
          "portal-id": {
            "type": ["null", "integer"]
          },
          "page-url": {
            "type": ["null", "string"]
          },
          "title": {
            "type": ["null", "string"]
          }
        }
      }
    }
  }
}

这是字典的示例:

{
  "vid": 1000, 
  "portal-id": 2512,
  "is-contact": true,
  "profile-token": "dummy_profile_token",
  "profile-url": "dummy_profile_url",
  "form-submissions": [
    {
      "conversion-id": "127-798",
      "timestamp": 1484080167266,
      "form-id": "70fd-4b98-14796-777",
      "page-url": "https://example.com/landing-page-url",
      "title": "A new test form",
      "meta-data": []
    }
  ]
}

我也是python的新手,这有点太多了。 这是我尝试过的方法,但我不知道该怎么办。

def get_default(type_object):
    if type_object == 'object':
        new_dict = {}
    elif type_object == 'array':
        return []
    else:
        return ''    
def fill_fields_with_empty_str(record, schema):
if isinstance(schema['type'], list):
    type_obj = schema['type'][len(schema['type'])-1]
elif isinstance(schema['type'], str):
    type_obj = schema['type']

if type_obj == 'object':
    new_dict = {}
    for key in schema['properties'].keys():
        if not record.get(key):    
            record[key] = get_default(schema['properties'][key]['type'])
        new_dict[key] = fill_fields_with_empty_str(record[key], schema['properties'][key])
    return new_dict

elif type_obj == 'array':
    new_list = []
    type_obj = schema["items"]['type']
    if len(record) == 0:
        record = get_default(type_obj)
    for element in schema["items"]:
        new_list.append(fill_fields_with_empty_str(record, schema['items']))
    return new_list
else:
    return ''

0 个答案:

没有答案