python - 检查Python多级字典的最佳方法

标签 python

目前我正在使用以下方法,假设字典

data[a][b][c]

我使用:

if "a" in data and "b" in data["a"] and "c" in data["a"]["b"]:
  ...

有没有更好的办法?

最佳答案

你可以把它包装在一个 try/except block 中

try:
    x = data[a][b][c]
    ...do stuff in your "if" clause
except KeyError:
    ...do stuff in your "else" clause

关于python - 检查Python多级字典的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20786839/

相关文章:

python - 有没有办法知道python中bytearray变量的长度?

python - NumPy 沿多维数组轴的最近值

python - 验证数据可以作为tensorflow.keras 2.0中的生成器吗?

python - Dataframe 到 numpy 数组中,值以逗号分隔

Python OAuth 错误 "Invalid Grant"

尽管传输存在,但 Python AsyncIO 由于缺少传输而无法创建协议(protocol)

python - 基于python中的 Pandas 索引在新列中添加值

python - 如何在 Python 中将匹配对聚合到 "connected components"

python - 我可以大约多少钱。使用 dvc 减少磁盘体积?

python - 如何获取XML中特定根的数据(通过python)