Python 如何确定dict中的哪个键有子dict?

Python 如何确定dict中的哪个键有子dict?,python,python-3.x,dictionary,recursion,Python,Python 3.x,Dictionary,Recursion,给定一个uuid,我想找到并返回包含uuid及其相关数据的dict。我写了一个测试来描述预期的结果 def test_search_for_cat(): cat_id=“a2c23d62-9d06-44f4-92dc-b28875173a54” cat_数据={ “高级开发人员”:{ “名称”:“高级开发人员”, “displayName”:“高级开发人员”, “uuid”:“418714f8-b3bd-4ba5-b4a7-4f87717419f4”, “中级开发人员”:{ “名称”:“中级开发

给定一个
uuid
,我想找到并返回包含
uuid
及其相关数据的dict。我写了一个测试来描述预期的结果

def test_search_for_cat():
cat_id=“a2c23d62-9d06-44f4-92dc-b28875173a54”
cat_数据={
“高级开发人员”:{
“名称”:“高级开发人员”,
“displayName”:“高级开发人员”,
“uuid”:“418714f8-b3bd-4ba5-b4a7-4f87717419f4”,
“中级开发人员”:{
“名称”:“中级开发人员”,
“displayName”:“中级开发人员”,
“uuid”:“a2c23d62-9d06-44f4-92dc-b28875173a54”,
},
}
}
检索的猫=搜索猫(猫id,猫数据)
断言已检索\u cat=={
“名称”:“中级开发人员”,
“displayName”:“中级开发人员”,
“uuid”:“a2c23d62-9d06-44f4-92dc-b28875173a54”,
}
我已经开始编写一个函数来搜索正确的类别

def搜索目录(目录id,目录数据):
如果存在(cat_数据,dict):
对于slug,cat_data.items()中的数据:
如果数据[“uuid”]==类别id:
返回数据
但我正在努力处理递归部分。当
uuid
与给定的
cat\u id
不匹配时,如何找到带有dict的键以传递给递归函数


你可以试试这个
isinstance(object,dict)
如果对象是dict,则返回
True
。 我们必须找到具有
cat\u id
作为映射到键的值的字典。 首先检查给定词典是否有
cat\u id
作为值,或者是否使用
dict.values()
。如果不是,则迭代值(如果值是字典),再次重复上述过程。如果中存在
cat\u id
,则返回我们正在迭代的当前词典

In [90]: cat_data
Out[90]:
{'senior-developer': {'name': 'senior-developer',
  'displayName': 'Senior Developer',
  'uuid': '418714f8-b3bd-4ba5-b4a7-4f87717419f4',
  'mid-level-developer': {'name': 'mid-level-developer',
   'displayName': 'Mid-level Developer',
   'uuid': 'a2c23d62-9d06-44f4-92dc-b28875173a54'}}}

In [91]: cat_id = "a2c23d62-9d06-44f4-92dc-b28875173a54"

In [94]: def recur(_dict,val):
    ...:     if val in _dict.values():
    ...:         return _dict
    ...:     else:
    ...:         for v in _dict.values():
    ...:             if isinstance(v,dict):
    ...:                 return recur(v,val)

In [95]: recur(cat_data,cat_id)
Out[95]:
{'name': 'mid-level-developer',
 'displayName': 'Mid-level Developer',
 'uuid': 'a2c23d62-9d06-44f4-92dc-b28875173a54'}

In [96]: retrived_cat=recur(cat_data,cat_id)

In [97]: retrived_cat
Out[97]:
{'name': 'mid-level-developer',
 'displayName': 'Mid-level Developer',
 'uuid': 'a2c23d62-9d06-44f4-92dc-b28875173a54'}
只需在return语句下面添加这个

isinstance(myObject,dict)

例如:

isinstance({},dict)

isinstance([],dict)

返回False

您可以使用
isinstance(object,dict)
返回
True
is object是一个dict。我实现了您的解决方案,但当我运行测试时,我得到:
AttributeError:'str'对象没有属性“值”
。我遗漏了什么?@RyanBrookePayne您必须先传递字典,然后传递一个字符串才能返回函数<代码>重复(字典,str\u to\u search)@RyanBrookePayne应该可以用。我复制了你在问题中发布的词典,即
cat_data
,我使用了你在问题中发布的
cat_id
。可能是您向函数传递了错误的参数。您是对的。我用错了参数。谢谢你的帮助。很好的解决方案。@RyanBrookePayne很高兴我的解决方案对您有所帮助。谢谢您的回复。不幸的是,我无法实施你的建议,因为没有上下文。你能以我在问题中发布的例子为例,添加你的代码,并更新你的答案吗?这将帮助我了解您在上下文中所说的内容。已修复,只需查找与
slug
键关联的值
\u dict
参数来自何处?在我的例子中,我没有这样做。我将
dict
改为
\u dict
,因为使用“
dict
”关键字来表示
dict
类型的变量不是一个好的做法,同样,最好不要调用
int
变量“
int
”,因为它非常混乱。换句话说,它与您的
dict
参数相同。
isinstance([],dict)