链接,嵌套的dict()在python中获取调用 [英] Chained, nested dict() get calls in python
问题描述
我使用dict.get('keyword')方法来询问一个嵌套的字典。目前我的语法是...
M = cursor_object_results_of_db_query
M中的m:
X = m.get(gparents)。get(parent)。get(child)
for x中的x:
y = x.get(key)
但是,有时候,父或子标签之一不存在,我的脚本失败。我知道使用 get()
我可以在默认情况下包含密钥不存在的形式...
get(parent,)或
pre>
get(parent,'orphan')
但是,如果我包含任何
Null
,''
,或空我可以想到,链接的.get(child)
失败时调用''。get(child)
因为没有方法
.get()
。
现在我正在解决这个问题的方法是在每个
.get之间使用一堆顺序的
调用,但这似乎是愚蠢的和愚蠢的---有一种方法来默认返回try-except
()skip
或pass
还是支持链接和智能失败的东西,而不是深入了解不存在的密钥?
理想情况下,我希望这是列表的理解形式:
[m.get(gparents)获得(母公司)。获得(孩子)for m in M]
但是,当缺席的父母导致
.get(child)
调用终止我的程序。解决方案都是python
dict
,你正在调用dict.get()
方法,你可以使用一个空dict
链接:[m.get(gparents {})。get(parent,{})。get(child)for m in M]
通过将最后一个
.get()
的默认值退回到无
。现在,如果没有找到任何中间密钥,链接的其余部分将使用空字典来查找内容,终止于.get('child')
返回无
。I'm interrogating a nested dictionary using the dict.get('keyword') method. Currently my syntax is...
M = cursor_object_results_of_db_query for m in M: X = m.get("gparents").get("parent").get("child") for x in X: y = x.get("key")
However, sometimes one of the "parent" or "child" tags doesn't exist, and my script fails. I know using
get()
I can include a default in the case the key doesn't exist of the form...get("parent", '') or get("parent", 'orphan')
But if I include any
Null
,''
, or empty I can think of, the chained.get("child")
fails when called on''.get("child")
since""
has no method.get()
.The way I'm solving this now is by using a bunch of sequential
try-except
around each.get("")
call, but that seems foolish and unpython---is there a way to default return"skip"
or"pass"
or something that would still support chaining and fail intelligently, rather than deep-dive into keys that don't exist?Ideally, I'd like this to be a list comprehension of the form:
[m.get("gparents").get("parent").get("child") for m in M]
but this is currently impossible when an absent parent causes the
.get("child")
call to terminate my program.解决方案Since these are all python
dict
s and you are calling thedict.get()
method on them, you can use an emptydict
to chain:[m.get("gparents", {}).get("parent", {}).get("child") for m in M]
By leaving off the default for the last
.get()
you fall back toNone
. Now, if any of the intermediary keys is not found, the rest of the chain will use empty dictionaries to look things up, terminating in.get('child')
returningNone
.这篇关于链接,嵌套的dict()在python中获取调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!