【发布时间】:2016-02-26 22:29:13
【问题描述】:
是否有一种简单、简洁的方法可以从嵌套的字典中获取值并获取 None(如果它不存在)?
d1 = None
d2 = {}
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))
【问题讨论】:
-
您的解决方案仅适用于 2 级嵌套字典。另外,当在不同级别找到相同的键时,您希望返回什么值?
-
您可以将两个
get方法链接在一起。例如,只需从您的函数中返回return d.get("a").get('b') if d else None。这就是你要找的吗?
标签: python