Python中从多个嵌套字典中动态提取值的函数

7d7tgy0s  于 2023-04-08  发布在  Python
关注(0)|答案(3)|浏览(157)

问题陈述是编写一个函数,该函数将接受输入字典对象并返回所有值的列表,即使在输入字典对象内部嵌套多级字典的情况下也是如此。
下面是这样一个嵌套字典的例子:

{
    "f_name": "AKASH",
    "s_name": "NASH",
    "professional": {
        "designation": "DE",
        "company": "XYZ",
        "place_of_work": {
            "city": "BLR",
            "state": "KA",
            "country": "IN"
        }
    },
    "personal_address": {
        "city": "EKM",
        "state": "KL",
        "country": "IN"
    }
}

我确实写了下面的代码,我能够提取字典值,即使是一个嵌套的字典,通过手动条件if语句。

def dic_values(x):
    l =[]
    l1 = []
    if type(x) == dict:
        for i in x:
            if type(x[i]) != dict:
                l.append(x[i])
            elif type(x[i])== dict:
                y = x[i]
                for j in y:
                    l1.append(y[j])
    else:
        "Please input a dict object"
    l.extend(l1)
    return l

案例1:
在运行函数时,dict对象内部有一个嵌套字典:

dic_values({"name":"AKASH","s_name":"NASH", "place":{"city":"BLR","state":"KA","country":"IN"}})

预期输出:

['AKASH', 'NASH', 'BLR', 'KA', 'IN']

案例二:
像下面的例子一样,在内部有一个多级嵌套字典的输入:

dic_values({"f_name":"AKASH","s_name":"NASH","professional":{"designation":"DE","company":"XYZ","place_of_work":{"city":"BLR","state":"KA","country":"IN"}}, "personal_address":{"city":"EKM","state":"KL","country":"IN"}})

输出:

['AKASH','NASH','DE','XYZ', {'city': 'BLR', 'state': 'KA', 'country': 'IN'}, 'EKM', 'KL', 'IN']

预期输出:

['AKASH','NASH','DE','XYZ', 'BLR', 'KA', 'IN', 'EKM', 'KL', 'IN']

问题:
假设在输入字典对象中存在嵌套字典。我想写一段代码,其中代码动态检查多级嵌套字典的存在并执行。如CASE 2预期输出。

pu82cl6c

pu82cl6c1#

修改现有代码以递归调用dic_values:

def dic_values(x):
    if not isinstance(x, dict):
        return [x]
    res = []
    for v in x.values():
        res.extend(dic_values(v))
    return [v for v in res if not isinstance(v, dict)]
fafcakar

fafcakar2#

如果你有兴趣以非递归的方式来做这件事。你可以在你去的时候维护一个字典堆栈。只要堆栈中有字典,就有更多的值可以找到:

def dic_values(d):
    assert isinstance(d, dict), "Please pass a dict"
    
    values = [] # this will hold the values
    stack = [d] # this should only contain dicts 
    
    while stack:
        next_d = stack.pop()
        for v in next_d.values():
            if isinstance(v, dict):
                stack.append(v) # put it back to process more
            else:
                values.append(v) # this a not dict, add it to the return list
    return values
        
        
dic_values({"f_name":"AKASH","s_name":"NASH","professional":{"designation":"DE","company":"XYZ","place_of_work":{"city":"BLR","state":"KA","country":"IN"}}, "personal_address":{"city":"EKM","state":"KL","country":"IN"}})
# ['AKASH', 'NASH', 'EKM', 'KL', 'IN', 'DE', 'XYZ', 'BLR', 'KA', 'IN']
xuo3flqw

xuo3flqw3#

def all_dict_values(input_dict):
    result = []
    for value in input_dict.values():
        if isinstance(value, dict):
            result.extend(all_dict_values(value))
        else:
            result.append(value)
    return result

相关问题