Home > Mobile >  How to deal with a key that is present and missing at the same type?
How to deal with a key that is present and missing at the same type?

Time:06-16

I am pulling data via API in a JSON response.

Here is how the data looks like

{
  "data": [
    {
      "register_overwrite_notify": false,
      "owner_id": "example",
    }
  ]
}

I am looking to save each owner id into a list however sometimes the owner_id does not exist.

How do I continue saving each owner id as long as the key exists and then if the key does not exist how do I "ignore" that record?

Here is some sample of code but this saves an empty list:

for each in users['data']:
    while 'owner_id' in users:
        accounts.append((each['owner_id']))

CodePudding user response:

How about the following solution:

data = [
    {
        "register_overwrite_notify": False,
        "owner_id": "example",
    }
]

accounts = []
for each in data:
    if each.get("owner_id") is not None:
        accounts.append(each.get("owner_id"))

All it does is it first checks if the dict.get() method returns something, otherwise it returns None, and the owner_id is not added to the accounts list.

CodePudding user response:

You can do this iteratively if you want:

my_list = []

resp = users.get("data", {})
if resp.get("data"):
    data = resp.get("data", [])
    if data:
        for item in data:
            owner_id = item.get("owner_id", None)
            if owner_id:
                my_list.append(owner_id)
  • Related