python - 链式嵌套 dict() 在 python 中获取调用

标签 python dictionary list-comprehension

我正在使用 dict.get('keyword') 方法查询嵌套字典。目前我的语法是...

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")

但是,有时“父”或“子”标签之一不存在,我的脚本会失败。我知道使用 get() 如果表单的键不存在,我可以包含一个默认值...

get("parent", '') or
get("parent", 'orphan') 

但如果我包含任何 Null'' 或我能想到的空,则链接的 .get("child")''.get("child") 上调用时失败,因为 "" 没有方法 .get()

我现在解决这个问题的方法是在每个 .get("") 调用周围使用一堆连续的 try-except ,但这似乎很愚蠢而且unpython---有没有办法默认返回 "skip""pass" 或者仍然支持链接和智能失败的东西,而不是深入研究键不存在?

理想情况下,我希望这是对表单的列表理解:

[m.get("gparents").get("parent").get("child") for m in M]

但是当缺少父级导致 .get("child") 调用终止我的程序时,这目前是不可能的。

最佳答案

由于这些都是python dict,并且您正在对它们调用 dict.get() 方法,因此您可以使用空的 dict 链接:

[m.get("gparents", {}).get("parent", {}).get("child") for m in M]

通过保留最后一个 .get() 的默认值,您可以退回到 None。现在,如果没有找到任何中间键,则链的其余部分将使用空字典进行查找,以 .get('child') 结束,返回 None.

关于python - 链式嵌套 dict() 在 python 中获取调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14484386/

相关文章:

javascript - 使 Leaflet 侧边栏 div 在标记单击时处于事件状态,反之亦然

python - 为什么列表理解不过滤掉重复项?

python - ImageOps.unsharp_mask 不适用于 PIL

python - I18N 使用 Django/Python

python - 字典维恩图的哈希或字典?

python - 可以在其方法中使用列表理解派生吗?

python - 在列表中查找唯一的元组(忽略顺序),同时在 python 中保留其他元组的原始顺序?

python - 将任意数量的输入从 python 发送到 .exe

python - 无法使用 upstart/supervisord 运行 uwsgi

c - 跳鱼词典