I have such a json file that combines all previous data storing versions. An example would be like this:
myList = {1: {'name': 'John', 'age': '27', 'class'= '2', 'drop' = True},
2: {'name': 'Marie', 'other_info': {'age': '22', 'class'= '3', 'dropped'= True }},
3: {'name': 'James', 'other_info': {'age': '23', 'class'= '1', 'is_dropped'= False}},
4: {'name': 'Lucy', 'some_info': {'age': '20', 'class'= '4', 'other_branch': {'is_dropped' = True, 'how_drop'= 'Foo'}}}}
I want to reach the information that contains drop
in the key or subkey . I don't know all the dictionary structures, there can be 20 or more. All I know is that they all contain the phrase 'drop'. There might be other phrases that might contain the phrase 'drop', as well but they are not too much. If there are multiple drops, I can manually adjust which one to take.
I tried to flatten, but after flattening every dictionary item had a different key name.
There are other information I'd like to reach but most of these attributes have the similar problem, too.
I want to get the True, True, False, True
values in the drop
, dropped
, and is_dropped
keys.
How can I reach this node?
CodePudding user response:
Create a recursive function to search and adds to the incrementally keys. Without putting in details in safety checks, you can do something like this:
def find(input_dict, base='', search_key='drop'):
found_paths = []
if search_key in input_dict.keys():
found_paths.append(base)
for each_key in input_dict.keys():
if isinstance(input_dict[each_key], dict):
new_base = base '.' each_key
found_paths = find(input_dict[each_key], base=new_base, search_key=search_key)
return found_paths
CodePudding user response:
You can use recursion to solve this:
def get_drop(dct):
for key, val in dct.items():
if isinstance(key, str) and 'drop' in key and isinstance(val, bool):
yield val
elif isinstance(val, dict):
yield from get_drop(val)
print(list(get_drop(myList)))
[True, True, False, True]