Kevin
Kevin

Reputation: 381

How do you check for nested dictionary structure in python?

Is there a way to ensure that a dictionary is not nested?

For example

key and value atomic

{key1: value1, key2: value2}

value is not atomic

{key1: {inner_key11: inner_value11}}

One way is to check the type, however there seems to be varies of other flavor of dictionary also, eg. defaultdict

Upvotes: 0

Views: 1073

Answers (2)

Alex Huszagh
Alex Huszagh

Reputation: 14614

You can check if the value inherits from a Mapping class. Defaultdict is a type of dict, and OrderedDict directly inherits from dict.

>>> from collections import Mapping

>>> d1 = {key1: value1, key2: value2}
>>> d2 = {key1: {inner_key11: inner_value11}}

>>> print isinstance(d1[key1], Mapping)
False
>>> print isinstance(d2[key1], Mapping)
True

Upvotes: 1

abarnert
abarnert

Reputation: 365797

One way is to check the type, however there seems to be varies of other flavor of dictionary also, eg. defaultdict

This is exactly why the idiomatic way to check types is to use isinstance. Since defaultdict is a subclass of dict, isinstance(x, dict) will be true for a defaultdict.

Also, you may want to look at collections.abc (or collections, in 3.2 and earlier) and see if dict is really what you want to check for. If you want to catch any mappings, even things like a blist.sorteddict, you'd check isinstance(x, collections.abc.Mapping). Or, if you want to catch any container at all (including sequences, sets, etc.), collections.abc.Container. Or maybe you want collections.abc.Iterable. You can read the descriptions and decide which one means "not atomic" for your use case.

Upvotes: 3

Related Questions