What is the pythonic way to access nested dicts without NoneType errors?
I have a deep nested dict (decoded from JSON, from the Instagram API). My initial code was like this: caption = post['caption']['text'] But that would throw a NoneType or KeyError error if the 'caption' key or the 'text' key doesn't exist. So I came up with this: caption = post.get('caption', {}).get("text") Which works, but I'm not sure about the style of it. For instance, if I apply this technique to one of the deeper nested attributes I'm trying to retrieve, it looks pretty ugly: image_url = post.get('images',{}).get('standard_resolution',{}).get('url') Is there a better, more pythonic, way
0 upvotes
View original discussion ↗
Comments
Sign in or sign up to comment and upvote.
No comments yet.