Rajeev
Rajeev

Reputation: 46909

get a key from a dictionary inside a dictionary

What is the easiest way to say whether the key div exist or not

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

di.get("div","Not found")  # prints not found

Upvotes: 4

Views: 101

Answers (5)

James Sapam
James Sapam

Reputation: 16930

Just trying to solve using regex, which is not the way to solve your problem. But this is fast .

#!/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)

Output:

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

Upvotes: 0

falsetru
falsetru

Reputation: 368944

You need to make a function that recursively check 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

Upvotes: 3

jonrsharpe
jonrsharpe

Reputation: 121975

In this precise case, you could use

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

More generally, if you don't know (or care) where 'div' is within di, you will need a function to search through the various sub-dictionaries.

Upvotes: 1

hd1
hd1

Reputation: 34657

First, flatten the dictionary:

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

Now check membership in the keys array. Note this will not tell you how many instances of div there are. just that at least 1 is present.

Upvotes: 0

GVH
GVH

Reputation: 414

You must do a deep search for it.

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

Upvotes: 0

Related Questions