Get the key to the dictionary inside the dictionary

What is the easiest way to tell if a key exists divor not

di = {
    'resp': {
        u'frame': {
            'html': {
                'div': [
                    u'test1'
                ]
            }
        }
    }
}

di.get("div","Not found")  # prints not found
+4
source share
5 answers

You need to make a function that recursively checks the nested dictionary.

def exists(d, key):
    return isinstance(d, dict) and \
           (key in d or any(exists(d[k], key) for k in d))

Example:

>>> di = {
...     'resp': {
...         u'frame': {
...             'html': {
...                 'div': [
...                     u'test1'
...                 ]
...             }
...         }
...     }
... }
>>>
>>> exists(di, 'div')
True
>>> exists(di, 'html')
True
>>> exists(di, 'body')  # Not exist
False
>>> exists(di, 'test1') # Not a dictionary key.
False
+3
source

In this exact case you can use

if 'div' in di['resp'][u'frame']['html']:

More generally, if you do not know (or do not care) where it 'div'is located inside di, you will need a function to search through various sub-dictionaries.

+1
source

.

def rec_search(d):
    for key in d.keys():
        if key == 'div': return True
    for value in d.values():
        if isinstance(value, dict) and rec_search(value): return True
    return False
0

:

def flatten_dict(d):
    for k,v in d.items():
        if isinstance(v, dict):
            for item in flatten_dict(v):
                yield [k]+item
        else:
            yield v

keys. , , div . 1 .

0

regex, . .

#!/usr/bin/python

di = {
    'resp': {
        'frame': {
            'html': {
                'div': [
                    'test1'
                ]
            }
        }
    }
}

import re
def check(k):
    key = di.keys()
    string = str(di.values())
    if k in key:
        return True
    try:
        m = re.findall('({[\"\']%s[\"\'])' % k, string)[0]
        if m and re.match('{', m):
            return True
        else:
            return False
    except:
        return False

for i in ['resp', 'abc', 'frame', 'div', 'yopy', 'python', 'test1']:
    print i, check(i)

:

resp True
abc False
frame True
div True
yopy False
python False
test1 False
0

Source: https://habr.com/ru/post/1526111/


All Articles