如何从嵌套字典获取值?
是否有一种简单明了的方法来从嵌套字典中获取值,None
如果不存在则获取该值?
d1 = Noned2 = {}
d3 = {"a": {}}
d4 = {"a": {"b": 12345}}
ds = [d1, d2, d3, d4]
def nested_get(d):
# Is there a simpler concise one-line way to do exactly this, query a nested dict value, and return None if
# it doesn't exist?
a_val = d.get("a") if d else None
b_val = a_val.get("b") if a_val else None
return b_val
if __name__ == "__main__":
bs = [nested_get(d) for d in ds]
print("bs={}".format(bs))
回答:
这应该工作:
def nested_get(d, *keys): for key in keys:
if d is None:
break
d = d.get(key)
return d
以上是 如何从嵌套字典获取值? 的全部内容, 来源链接: utcz.com/qa/410630.html