查找字典是简单的键值对还是嵌套的字符串

时间:2015-03-27 12:27:09

标签: python dictionary

我有两个词典,一个是简单的键值对,另一个是嵌套词典的集合。

简单字典:

{
   "key1" : "value1",
   "key2" : "value2",
   "key3" : "value3"
}

嵌套词典:

{
  "key1" : {
      "key2" : "value2",
      "key3" : "value3",
      "key4" : "value4"
      }
  "key5" : {
      "key6": "value6",
      "key7" : "value7"
      }
 }

我想知道dict是简单还是嵌套,我该怎么做呢?

1 个答案:

答案 0 :(得分:4)

你可以循环显示dict中的所有值,并检查它们中的任何一个是否是dict:

>>> d = {
...   "key1" : {
...       "key2" : "value2",
...       "key3" : "value3",
...       "key4" : "value4"
...       },
...   "key5" : {
...       "key6": "value6",
...       "key7" : "value7"
...       }
...  }
>>> any(isinstance(value, dict) for value in d.values())
True

上面代码中的any将启用支票短路。

对于简单的非嵌套字典,相同的检查返回False:

>>> d = {"key2" : "value2",
... "key3" : "value3",
... "key4" : "value4"}
>>> any(isinstance(value, dict) for value in d.values())
False