0

I have this piece of code (below). I have data in json file and I fetch the data (code below). I zip these values and write them to csv file. My issue is that if any of the value doesn't exist in try I want to put a 'None' over there for that value. What I tried (I think is lame) -> I added try and except for each values that I am fetching below. I need help in writing this better.

The Exception tells me what value is missing. For example, code is missing. So how to I deal with this in except and put None for code?

 for i in range(len(res_1)):
        try:
            gp_code.append(res_1[i]['metadata']['annotations']['code'])
            ticket.append(res_1[i]['metadata']['annotations']['ticket'])
            node.append(res_1[i]['metadata']['annotations']['node-selector'])
            display_name.append(res_1[i]['metadata']['name'])
            status.append(res_1[i]['status']['phase'])
            timer.append(res_1[i]['metadata']['creationTimestamp'])
            lifetime.append(res_1[i]['metadata']['annotations']['lifetime'])
        except Exception as e:
            print(e)
Heenashree Khandelwal
  • 659
  • 1
  • 13
  • 30
  • 2
    For a start, any time you write `for i in range(len(...))` you are almost certainly doing it wrong. You should always iterate over the thing itself: `for element in res_1` – Daniel Roseman Nov 15 '17 at 12:15
  • I think you need to read this https://stackoverflow.com/questions/6130768/return-none-if-dictionary-key-is-not-available as I think it will do what you want. i.e. return None when the key is not present. Also, you could simplify you code a bit by having a statement like `dict_metadata = res_1[i]['metadata']` to reduce the replicated parts of the nested dictionaries you're using. Up to you – R.Sharp Nov 15 '17 at 12:17
  • @R.Sharp, I get what you are saying. I should have tries this way. Thanks – Heenashree Khandelwal Nov 15 '17 at 12:20
  • Possible duplicate of [Return None if Dictionary key is not available](https://stackoverflow.com/questions/6130768/return-none-if-dictionary-key-is-not-available) – Serge Ballesta Nov 15 '17 at 12:25

1 Answers1

0

You can use get with appropriate default values and avoid exception handling alltogether:

for x in res_1:
    gp_code.append(x.get('metadata', {}).get('annotations', {}).get('code', None)
    # ...

Or you can put the exception/default value handling in a function:

def _append(lst, obj, *items):
    try:
        for item in items:
            obj = obj[item]
        lst.append(obj)
    except KeyError:
        lst.append(None)

for x in res_1:
    _append(gp_code, x, 'metadata', 'annotations', 'code')
    # ...
user2390182
  • 72,016
  • 6
  • 67
  • 89