Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a dictionary is nested - python

DON'T FORGET, SEE MY SELF-ANSWER BELOW

Let's say i have a dictionary called d:

d = {'a': {1: (1,2,3), 2: (4,5,6)},'b': {1: (3,2,1), 2: (6,5,4)}}

As you can see, it is a nested dictionary, how would i detect if it is?


Here are some examples:

d = {'a':{1:(1,2,3),2:(4,5,6)},'b':{1:(3,2,1),2:(6,5,4)}}
d = {'a':1,'b':2}

I want the output:

True
False

P.S. list of dictionaries don't count.

like image 393
U12-Forward Avatar asked Apr 21 '26 02:04

U12-Forward


1 Answers

Use any:

print(any(isinstance(i,dict) for i in d.values()))

First dictionary will return:

True

Second will:

False

To explain:

  1. Go and iterate trough d's values.

  2. Use isinstance to check whether if the type is dict or not.

  3. Use an outer any to check if there are any elements that are True (are dictionaries).

There you go now, it will work.

like image 72
U12-Forward Avatar answered Apr 23 '26 15:04

U12-Forward