【问题标题】:how to recursively check a nested dictionary keys and return specific value如何递归检查嵌套字典键并返回特定值
【发布时间】:2022-01-15 19:14:55
【问题描述】:

我有一个带有嵌套字典和一个特定数字的函数(在我编写的代码中等于 1) 我需要编写一个遍历字典并仅返回映射到等于特定选择数字的键的值的递归函数 这是我写的

def nested_get(d, key):
res=[]
for i in d.keys():
    if i == key:
        res.append(d[i])
        return res
    if type(d[i]) is dict:
        another = nested_get(d[i], key)
        if another is not None:
            return res + another
return []

print(nested_get({1:{1:"c",2:"b"},2:"b"},1))

我需要它返回 ['c'] 但它返回 [{1:'c',2:'b'}]

【问题讨论】:

  • 交换 if 的。检查之前是dict
  • 你没有返回 None - 删除最后一个 return [] 或检查空列表
  • 缩进错误

标签: python dictionary recursion


【解决方案1】:

您的程序永远不会到达if type(d[i]) is dict:,因为它在for 循环的第一次迭代中的第一个if 语句中返回。

首先检查存储在键中的值是否为dict,直到if 语句之后才返回。最后不需要return [],因为如果没有附加任何内容,res 将是空的。

def nested_get(d, key):
    res=[]
    for i in d.keys():
        if type(d[i]) is dict:
            res.extend(nested_get(d[i], key))
        else:
            if i == key:
                res.append(d[i])
    return res

print(nested_get({1:{1:"c",2:"b"},2:"b"},1))
print(nested_get( {1:{1:"a",2:"b"},2:{1:{1:"c",2:"b"},2:"b"}},1))

【讨论】:

  • 当我尝试使用更深层的嵌套字典时,例如 {1:{1:"a",2:"b"},2:{1:{1:"c",2:" b"},2:"b"}} 并且键是 1 它只返回 ['a'] 而它应该返回 ['a','c']
  • 啊,确实如此。应该只在 for 循环结束时返回。已相应地编辑了代码。
  • 顺便说一句,如果您以前没有遇到过,extend 是您在原始代码中使用的if another is not None...res + another 模式的更简洁的替代方案。
  • 非常感谢!!!
猜你喜欢
  • 2021-12-16
  • 2019-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-18
  • 2021-04-10
  • 2020-05-14
  • 2021-10-14
相关资源
最近更新 更多