简体   繁体   中英

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

PS list of dictionaries don't count.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM