How to search for values in a multi-level nested dictio…
To search for the values in a deeply nested dictionary, you can use a recursive method. Here is an example code:
def find_value(nested_dict, keys):
if len(keys) == 1:
return nested_dict.get(keys[0])
else:
key = keys[0]
if key in nested_dict:
return find_value(nested_dict[key], keys[1:])
else:
return None
# 示例字典
example_dict = {
'a': {
'b': {
'c': 123
}
}
}
# 查找值
keys = ['a', 'b', 'c']
value = find_value(example_dict, keys)
print(value) # 输出: 123
In this example, the find_value function takes two parameters: nested_dict representing a nested dictionary, and keys representing the list of keys to search for. The function first checks the length of the keys list. If it only has one element, it directly returns the corresponding value. If the length of the keys list is greater than 1, it takes the first key as the key at the current level and searches for the corresponding value in nested_dict. If the key exists, the find_value function is recursively called to continue searching for the value at the next level; if the key does not exist, it returns None to indicate that it was not found.
By calling the find_value function with the example dictionary example_dict and the keys to search for [‘a’, ‘b’, ‘c’], it will return the value 123.