0

I have an object I'm creating and sometimes it's not going to be created i.e. None.

I perform the following dic.get("findThis") but since dic is sometimes None It will return AttributeError: 'NoneType' object has no attribute 'get'

There are a few solutions like checking the dic for existence using

if not dic: 
  print "MISSING" 
else: 
  #do your stuff`. 

What's a better way to do this?

mdml
  • 22,442
  • 8
  • 58
  • 66
Sten Kin
  • 2,485
  • 3
  • 23
  • 29
  • 3
    Without the context of your specific problem I think your approach is the best on those cases. But maybe in a more specific situation there is a better way. – Alvaro Fuentes Feb 21 '14 at 19:28
  • there is nothing wrong with your solution. unless you don't want to print missing for an empty dict, in which case you'd want to do if dic is not None – Brian Schlenker Feb 21 '14 at 20:04

2 Answers2

3

Are you looking for a ternary operator?

result = dic.get("findThis") if dic else None

Kirill Zaitsev
  • 4,511
  • 3
  • 21
  • 29
  • No that's not it. For example let's say I do something like `[dic.get("findThis"),dic.get("findThis2"),dic.get("findThis3"),dic.get("findThis4"),dic.get("findThis5"),dic.get("findThis6")]`, They should all return "MISSING" and not have to do a check for each. – Sten Kin Feb 21 '14 at 19:34
  • 1
    Can you elaborate? Why is it possible for dic to become None, it seems like you should just use an empty dict instead of None as a default value. – Kirill Zaitsev Feb 21 '14 at 19:37
  • The `dic` is returned from a json response sometimes it's missing. – Sten Kin Feb 21 '14 at 19:55
  • Then why don't you check it once and substitute with empty dict if it's None? It's common practice to do smth like `if not x: x = {}` Especially when passing empty parameters to a function or deserialising some values. – Kirill Zaitsev Feb 21 '14 at 20:22
0

You can use a defaultdict an use it like this:

import collections

#example function returning the dict
def get_dict_from_json_response():
    return {'findThis2':'FOUND!'}

defdic = collections.defaultdict(lambda: 'MISSING')

#get your dict
dic = get_dict_from_json_response()

if dic:
   defdic.update(dic) #copy values

dic = defdic #now use defaultdict
print [dic["findThis"],dic["findThis2"],dic["findThis3"],dic["findThis4"],dic["findThis5"],dic["findThis6"]]

Output:

['MISSING', 'FOUND!', 'MISSING', 'MISSING', 'MISSING', 'MISSING']
Alvaro Fuentes
  • 16,937
  • 4
  • 56
  • 68