简体   繁体   English

在python中,有没有办法自动替换缺失值?

[英]In python, is there a way to automatically substitute for missing values?

I'm trying to parse a JSON object that consists of an array of objects. 我正在尝试解析一个由一组对象组成的JSON对象。 Each object contains several fields, but fields are often missing. 每个对象包含多个字段,但通常缺少字段。 Here's an example: 这是一个例子:

{
    'objects' : [{
        'fieldA' : 1,
        'fieldB' : 2,
        'fieldC' : 3,
    },
    {
        'fieldA' : 7,
        'fieldC' : 8,
    },
    {},
    {
        'fieldB' : 1,
        'fieldC' : 0,
    }]
}

I'd like to convert each of the fields into a list, preserving the ordering of the objects, the equivalent of this: 我想将每个字段转换为一个列表,保留对象的顺序,相当于:

fieldA = [1,7,"Missing","Missing"]
fieldB = [2,"Missing","Missing",1]
fieldC = [3,8,"Missing",0]

Is there a simple way to do this? 有一个简单的方法吗? I can come up with ways to do it that involve a lot of 'if' and 'in' statements and repeated iteration over lists. 我可以想出办法,包括很多'if'和'in'语句以及重复迭代列表。 But it seems like there should be a more pythonic way to do it, something like: 但似乎应该有更多的pythonic方式来做到这一点,例如:

fieldA = [ (obj.fieldA | "missing") for obj in json.objects]

Does python syntax allow something like this? python语法是否允许这样的东西?

You need the dict.get() method: 你需要dict.get()方法:

fieldA = [obj.get("fieldA", "missing") for obj in json["objects"]]

Note that the items of a dictionary are accessed with ["key"] , not with .key . 请注意,使用["key"]访问字典的项目,而不是使用.key

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

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