什么是pythonic方式来访问嵌套的小数点,没有NoneType错误 [英] What is the pythonic way to access nested dicts without NoneType errors

查看:135
本文介绍了什么是pythonic方式来访问嵌套的小数点,没有NoneType错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个深层嵌套的dict(从json解码,从instagram api)。
我的初始代码是这样的:

  caption = post ['caption'] ['text'] 

但是,如果'caption'键或'text'键不成功,则会抛出NoneType或KeyError错误存在。



所以我想出了这个:

 标题= post.get('caption',{})。get(text)

哪些工作,但我不知道它的风格。例如,如果我将这种技术应用于我想要检索的更深入的嵌套属性之一,它看起来很丑陋:

  image_url = post.get('images',{})get('standard_resolution',{})get('url')

有没有更好的,更多的pythonic的方式来写这个?我的目标是检索数据,如果它在那里,但如果不存在,则不能执行。



谢谢!

解决方案

最奇怪的方法是简单地捕捉 KeyError

  try:
caption = post ['caption'] ['text']
除了KeyError:
caption =无

这是一个简单,明显的,可以直接被Python程序员理解的。


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 to write this? My goal is to retrieve the data, if it's there, but not to hold up execution if it's not there.

Thanks!

解决方案

The most Pythonic way would be simply to catch the KeyError:

try:
    caption = post['caption']['text']
except KeyError:
    caption = None

This is simple, obvious, and immediately understandable to a Python programmer.

这篇关于什么是pythonic方式来访问嵌套的小数点,没有NoneType错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆