federica
federica

Reputation: 43

How can I check if a dictionary contains a dictionary?

I'm looking for a function that return true if in my dictionary contain another dictionary.

for k in dictObj.iteritems():
    if k contain dictionary return false
    else return true

Is there a straightforward way to do this?

Upvotes: 1

Views: 80

Answers (2)

Tim
Tim

Reputation: 43314

You're looking for something like this

def has_inner_dict(d):
    for v in d.values():
        if isinstance(v, dict):
            return True
    return False

Upvotes: 3

Martijn Pieters
Martijn Pieters

Reputation: 1121834

You can loop over the values (so over dict.itervalues() or dict.values(), depending on your Python version), and use isinstance() to test each. Combine that with the any() function and a generator expression to make it efficient:

return any(isinstance(v, dict) for v in dictObj.itervalues())

Demo:

>>> dictObj = {'foo': 'bar'}
>>> any(isinstance(v, dict) for v in dictObj.itervalues())
False
>>> dictObj = {'foo': {'spam': 'eggs'}}
>>> any(isinstance(v, dict) for v in dictObj.itervalues())
True

If you want to detect any mapping type (not just dictionaries), you could test for collections.Mapping instead of dict; this would let you handle any alternative mapping implementations too.

Upvotes: 6

Related Questions