【问题标题】:How do I determine which key in a dict has a child dict?如何确定字典中的哪个键有子字典?
【发布时间】:2020-02-05 19:52:10
【问题描述】:

给定一个uuid,我想查找并返回包含uuid 和与之关联的数据的dict。我写了一个测试来描述预期的结果。

def test_search_for_cat():
    cat_id = "a2c23d62-9d06-44f4-92dc-b28875173a54"
    cat_data = {
        "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",
            },
        }
    }

    retreived_cat = search_for_cat(cat_id, cat_data)

    assert retreived_cat == {
        "name": "mid-level-developer",
        "displayName": "Mid-level Developer",
        "uuid": "a2c23d62-9d06-44f4-92dc-b28875173a54",
    }

我已经开始编写一个函数来搜索正确的类别。

def search_for_cat(cat_id, cat_data):
    if isinstance(cat_data, dict):
        for slug, data in cat_data.items():
            if data["uuid"] == cat_id:
                return data

但我在递归部分苦苦挣扎。当uuid 与给定的cat_id 不匹配时,如何找到带有dict 的键以传递给递归函数?

【问题讨论】:

  • 你可以使用isinstance(object,dict)返回True是对象是一个字典。

标签: python python-3.x dictionary recursion


【解决方案1】:

你可以试试这个。如果 objectdictisinstance(object,dict) 返回 True。 我们必须找到将cat_id 作为映射到键的值的字典。 首先使用dict.values()检查给定字典是否有cat_id作为值。如果不是,则遍历值,如果该值是 字典,则再次重复上述过程。如果cat_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'}

【讨论】:

  • 我实现了您的解决方案,但是当我运行测试时,我得到:AttributeError: 'str' object has no attribute 'values'。我错过了什么?
  • @RyanBrookePayne 您必须将字典后跟一个字符串传递给函数 recur 。 recur(dictionary,str_to_be_searched).
  • @RyanBrookePayne 它应该可以工作。我复制了您在问题中发布的字典,即cat_data,并使用了您在问题中发布的cat_id。可能是你给函数传递了错误的参数。
  • 你是对的。我使用的参数错误。谢谢您的帮助。很好的解决方案。
  • @RyanBrookePayne 很高兴我的解决方案对您有所帮助。
【解决方案2】:

isinstance(myObject,dict)

例如:

isinstance({},dict)

返回真

isinstance([],dict)

返回假

【讨论】:

  • 感谢您的回复。不幸的是,由于没有上下文,我无法实施您的建议。您能否以我在问题中发布的示例,将您的代码添加到其中并更新您的答案?这将帮助我了解您在上下文中所说的内容。
【解决方案3】:
if is_instance(slug, _dict):
    search_for_cat_id(cat_id, _dict[slug])

只要在return语句下面加上这个

【讨论】:

  • 已修复,只需要找到与slug 键关联的值
  • _dict 参数从何而来?我的示例中没有。
  • 我将dict 更改为_dict,因为使用'dict' 关键字来表示dict 类型的变量不是一个好习惯,同样最好不要调用int变量'int',因为它令人困惑。换句话说,它与您的 dict 参数相同。
猜你喜欢
  • 2014-12-02
  • 1970-01-01
  • 2018-09-02
  • 2016-08-14
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2021-12-27
  • 1970-01-01
相关资源
最近更新 更多