[英]Get value from asymmetrically nested dict with unique keys
假设我有一个嵌套的字典,嵌套不对称,并且在整个嵌套字典中没有键出现超过一次:
d = {
'd1' : {'d11': 'a', 'd12': 'b'},
'd2' : {'d21': 'c', 'd22': {'d221': 'd', 'd222': 'e'}}
}
我想要一个函数(没有模块)返回任何(唯一)键的值,即:
def get_some_val(d, key):
...
return val_of_that_key
谁能在正确的方向上帮助我? 谢谢!
我尝试将(嵌套的)键作为字符串传递,然后使用 exec 获取值,但这没有用
一种方法:
d = {
"d1": {"d11": 'a', "d12": 'b'},
"d2": {"d21": 'c', "d22": {"d221": 'd', "d222": 'e'}}
}
def nested_find(needle, haystack):
if needle in haystack:
return haystack[needle]
for v in haystack.values():
if isinstance(v, dict):
val = nested_find(needle, v)
if val:
return val
res = nested_find("d222", d)
print(res)
输出
e
一种单线替代方法是:
def nested_find(needle, haystack):
gen = (val for v in haystack.values() if isinstance(v, dict) and (val := nested_find(needle, v)))
return haystack.get(needle, next(gen, None))
如果叶键确实是唯一的,那么您可以将字典展平:
d = {
'd1' : {'d11': 'a', 'd12': 'b'},
'd2' : {'d21': 'c', 'd22': {'d221': 'd', 'd222': 'e'}}
}
def flattendict(d):
res = {}
def _flatten_subdict(d, res):
for k, v in d.items():
if not isinstance(v, dict):
res[k] = v
else:
_flatten_subdict(v, res)
_flatten_subdict(d, res)
return res
print(flattendict(d))
哪个打印
{'d11': 'a', 'd12': 'b', 'd21': 'c', 'd221': 'd', 'd222': 'e'}
IE。 只有唯一键的字典。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.