Search Nested Dictionaries in Python
To search for values in a multi-layer nested dictionary, you can achieve this by using recursion. Recursion is a method of a function calling itself, allowing it to search through each layer of the nested dictionary until it finds the desired value or traverses through all dictionaries.
Below is an example code demonstrating how to use recursion to search for values in a dictionary with multiple nested layers.
def find_value(dictionary, target_key):
for key, value in dictionary.items():
if key == target_key:
return value
elif isinstance(value, dict):
result = find_value(value, target_key)
if result is not None:
return result
return None
# 示例字典
my_dict = {
'a': 1,
'b': {
'c': 2,
'd': {
'e': 3,
'f': 4
}
}
}
# 查找值
result = find_value(my_dict, 'f')
print(result) # 输出: 4
In the example above, the function find_value takes two parameters: dictionary, which represents the dictionary to search, and target_key, which represents the key to look for. The function iterates through the key-value pairs of the dictionary, and if the current key is equal to the target key, it returns the corresponding value. If the current value is a dictionary, the find_value function is called recursively to continue searching the next level of the dictionary. If the target key is not found after iterating through all dictionaries, None is returned.
You can replace the dictionary and target key values in the sample code with your own data to achieve specific search functionality.