简体   繁体   中英

Search for key in nested Python dictonary

I want to search for key-value pairs in Python dict. My dict is nested, so simple solution like:

if 'keyname' in my_dict:
...

or:

for key, value in my_dict.items():
    if 'keyname' == key:

does not work for me. This is my dict:

my_dict = {'a': 111,
           'b': 222,
           'c':{'d': 333,
                'e': 444},
           'f':555,
           'g':{'h': {'i': 666}}}

And I want to find value of 'i' or 'd', whats the simplest way to do that? I do not care for name of the key that has nested dict. For example, I do not care for key name of 'c' or 'g' or 'h', I only care about key-values (key-number). Is there a way to transform my dict to look like this:

my_result = {'a': 111,
             'b': 222,
             'd': 333,
             'e': 444,
             'f': 555,
             'i': 666}

In that way it would be easy.

You can flatten the dictionary using recursion here.

def flat(data):
    out = {}
    for k, v in data.items():
        if isinstance(v, dict):
            out.update(flat(v))
        else:
            out[k] = v
    return out

flat(my_dict)
# {'a': 111, 'b': 222, 'd': 333, 'e': 444, 'f': 555, 'i': 666}

try this one:

def find_value(_key, _dict):
    for key, value in list(_dict.items()):
        if isinstance(value, dict):
            result = find_value(_key, value)
            if result:
                return result
        if key == _key:
            return value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM