簡體   English   中英

使用唯一鍵從非對稱嵌套字典中獲取值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM