tushman.io

The musings of an insecure technologist

Dict Digger

In the age or SaaS, and working with 3rd part APIs developers often have to navigate a complex object (arrays of hashes of arrays or hashes) (I am looking at you Adwords API)

I wanted a nice way to avoid doing None checks and does this key exist over and over again.

So I made a (very) simple utility to help with it dict_digger

And works like this …

1
pip install dict_digger
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import dict_digger

h = {
    'a': {
         'b': 'tuna',
         'c': 'fish'
     },
     'b': {}
}

result = dict_digger.dig(h, 'a','b')
print result  # prints 'tuna'

result = dict_digger.dig(h, 'c','a')
print result # prints None
# Important!!  Does not through an error, just returns None

#but if you like
result = dict_digger.dig(h, 'c','a', fail=True)
# raises a KeyError

# also support complex objects so ...

complex = {
    'a': {
         ['tuna','fish']
     },
     'b': {}
}
result = dict_digger.dig(complex, 'a',0)
print result #prints tuna

Alternatively you do the following

1
2
3
4
try:
    result = h['c']['a']
except KeyError:
    result = None

Find it on github here

Comments