Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

I'm trying to parse a JSON object that consists of an array of objects. 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. But it seems like there should be a more pythonic way to do it, something like:

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

Does python syntax allow something like this?

like image 626
Abe Avatar asked Jan 29 '26 06:01

Abe


1 Answers

You need the dict.get() method:

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

Note that the items of a dictionary are accessed with ["key"], not with .key.

like image 160
Sven Marnach Avatar answered Jan 30 '26 21:01

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!