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?

2
  • 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. Commented Feb 21, 2014 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 Commented Feb 21, 2014 at 20:04

2 Answers 2

3

Are you looking for a ternary operator?

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

Sign up to request clarification or add additional context in comments.

4 Comments

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.
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.
The dic is returned from a json response sometimes it's missing.
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.
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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.