0

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

2
  • why would you do this? if there are restrictions on the values, check those constraints (e.g.: "must be a number"). Commented Jun 11, 2015 at 23:37
  • 1
    The first question I like to ask in this sort of situation is "why do you want to do this?" The second question is "are you sure?" Commented Jun 11, 2015 at 23:38

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.