Categories
Python

Nested Dict Gets in python

Update- the below doesn’t work at all actually.. you do need to do a try-except block cause if any of the values are, for example NONE. The whole thing craps out with an exception.

I’ll leave the below to…. Show my workings!

Trying to figure out the best way to parse out complex JSON.

Saying

Level = issue.get('fields').get('customfield_1', 'NA')

Doesn’t actually work if ‘fields’ is missing. Error is:

AttributeError: 'NoneType' object has no attribute 'get'

you actually need to say:

In [1]: d = {'parent':{'test':True}}

In [2]: d
Out[2]: {'parent': {'test': True}}

In [3]: d.get('parent')
Out[3]: {'test': True}

In [4]: d.get('parentt')

In [5]: d.get('parent').get('test')
Out[5]: True

In [6]: d.get('parenT').get('test')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-142a5af0ba34> in <module>
----> 1 d.get('parenT').get('test')

AttributeError: 'NoneType' object has no attribute 'get'

In [7]: d.get('parenT', {}).get('test')

In other words, in the case of nested gets, make sure the second attribute (the one that returns if your key is missing) is an empty dict… ie {}

Categories
Python

Pop nested dict in python

I have struggled to find the following examples:

hello = {'a':{'b':2, 'c':3}}
#I want to pop c (which is nested in a)
hello.get('a').pop('c', None)

This took me too long to figure out