我有一个数组:
["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/