python - 在 Python 中使用数组递归查找字典中的元素

标签 python arrays dictionary recursion

我有一个数组:

["a", "1", "2"]

还有一个有点复杂的字典:

{
  "a":{
    "1": {
      "1": "Some text",
      "2": "This is the text I want",
      "3": "Even more"
    },
    "2": {
      "1": "Some text",
      "2": "More text"
    }
  },
  "b": {
    "1": "Here is some text",
    "2": {
      1: "Some text"
    },
    "3": {}
  }
}

我如何使用我的数组来获取“This is the text I want”?我是递归的新手,所以我真的不知道如何正确解决这个问题

最佳答案

这应该更容易一些:

keys = ["a", "1", "2"]
dictionary = {
  "a":{
    "1": {
      "1": "Some text",
      "2": "This is the text I want",
      "3": "Even more"
    },
    "2": {
      "1": "Some text",
      "2": "More text"
    }
  },
  "b": {
    "1": "Here is some text",
    "2": {
      1: "Some text"
    },
    "3": {}
  }
}

for key in keys: # drop to lower level of dictionary with each loop
    try:
        dictionary = dictionary[key]
    except KeyError:
        dictionary = 'ERROR'
        break
    
print(dictionary) # after the loop ends, 'dictionary' will hold the required value

关于python - 在 Python 中使用数组递归查找字典中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62916302/

相关文章:

python - 通过 Cython(回调)将 Python 函数应用于 std::vector

php - 如果不在其他数组中,则从数组中删除值,但保持相同的顺序

python - Python 中的字典

java - 一维java数组的问题

C - 反转字符串数组中单词的顺序

c++ - 无法将 map 插入 vector 内?

dictionary - 键声明,其值来自之前在同一映射初始化中定义的现有键

Python NumPy 'Expected an input array of unsigned byte data type'

python - 随机数网格 4 x 6 Python 3

python - python 3中使用非ascii字符进行编码/解码的问题