0

From JSON data I obtain a complicated dictionary strucutre. Say I want to obtain values such as temperature, which I can access by specifying a number of keys.

},
   "t": {
    "v": -4.1}

temp = float(json_object['data']['iaqi']['t']['v'])

Sometimes this data might not have say "t" and I get a KeyError. So I want to use the dictionary .get() method in order to avoid this, but it only takes 2 arguments. Is there a way I can use this method using 4 keys? Or is there an alternative approach to the KeyError problem I could try?

pjdavis
  • 325
  • 4
  • 25

2 Answers2

1

You can apply .get() on the last element obtained before 't'. Imagine this:

a = {'a' : { 'b' : [1, 2]}}
a['a'].get('b') # Returns [1, 2]
a['a'].get('c') # Empty

In your case, you can use:

json_object['data']['iaqi'].get('t')

From the last line, if you try to access ['v'] you will get an AttributeError. You can nest it as follows:

json_object['data']['iaqi'].get('t', {}).get('v')
#                                    ^------- will create an empty dict if 't' is not found
Carles Mitjans
  • 4,786
  • 3
  • 19
  • 38
  • Perfect!! Although is there any way i can have an empty string as the default. If I have ' ' in place of {} or within {} I get an error message. – pjdavis Feb 17 '17 at 15:40
1

You can do this:

In [69]: d
Out[69]: {'iaqi': {'t': {'v': -4.1}}}

In [70]: d.get('iaqi').get('t').get('v')
Out[70]: -4.1

In [71]: d.get('iaqi').get('a').get('v')
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-71-9f601d1c1fe4> in <module>()
----> 1 d.get('iaqi').get('a').get('v')

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

In [72]:

But!

The nonetype error for a key that doesn't exist will still leave you in the same situation.

I would suggest using a try/except block:

In [73]: try:
    ...:     print d['iaqi']['t']['v']
    ...: except KeyError:
    ...:     print "I handle this my way"
    ...:
-4.1

In [74]: try:
    ...:     print d['iaqi']['a']['v']
    ...: except KeyError:
    ...:     print "I handle this my way"
    ...:
I handle this my way
Kelvin
  • 1,357
  • 2
  • 11
  • 22