Reading from Python dict if key might not be present
If possible, use the simplejson library for managing JSON data.
There are two straightforward ways of reading from Python dict if key might not be present. for example:
dicty = {'A': 'hello', 'B': 'world'}
- The pythonic way to access a key-value pair is:
value = dicty.get('C', 'default value')
- The non-pythonic way:
value = dicty['C'] if dicty['C'] else 'default value'
- even worse:
try:
value = dicty['C']
except KeyError as ke:
value = 'default value'
The preferred way, when applicable:
for r in results:
print r.get('key_name')
this will simply print None
if key_name
is not a key in the dictionary. You can also have a different default value, just pass it as the second argument:
for r in results:
print r.get('key_name', 'Missing: key_name')
If you want to do something different than using a default value (say, skip the printing completely when the key is absent), then you need a bit more structure, i.e., either:
for r in results:
if 'key_name' in r:
print r['key_name']
or
for r in results:
try: print r['key_name']
except KeyError: pass
the second one can be faster (if it's reasonably rare than a key is missing), but the first one appears to be more natural for many people.