Last active
December 27, 2020 22:17
-
-
Save choeh/7172b8f7915e421af6acbf249a47e08c to your computer and use it in GitHub Desktop.
Find key(s) or value(s) in given json-like data dictionary by given target string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
Snippet for searching target string in key(s) or value(s) of nested dictionary | |
""" | |
def find_target_in_nested_dictionary(data: dict = None, target: str = None, level: int = 0, key_chain: str = 'data') -> dict: | |
""" Find key(s) or value(s) in given json-like data dictionary by given target string """ | |
if data is None or target is None: | |
return | |
for key, value in data.items(): | |
if (isinstance(key, str) and target in key): | |
# Current key is containing target | |
yield dict(level=level, chain=f"{key_chain}['{key}']", value=value) | |
elif (isinstance(value, str) and target in value): | |
# Current value is containing target | |
yield dict(level=level+1, chain=f"{key_chain}['{key}']", value=value) | |
elif isinstance(value, dict): | |
# Recursively dive into nested dictionary for current key | |
yield from find_target_in_nested_dictionary(value, target, level+1, f"{key_chain}['{key}']") | |
# Sample nested data dictionary | |
data = { | |
'0': { | |
'if': { | |
'query': 'volume > 500', | |
'column': 'volume', | |
}, | |
'backgroundColor': 'green', | |
'color': 'white' | |
}, | |
'1': { | |
'if': { | |
'query': 'price > 5 && price < 10', | |
'column': 'price' | |
}, | |
'backgroundColor': 'green', | |
'color': 'white' | |
}, | |
'2': { | |
'if': { | |
'query': 'ratio > -1 && ratio < 0', | |
'column': 'ratio' | |
}, | |
'backgroundColor': 'red', | |
'color': 'black' | |
}, | |
'3': { | |
'if': { | |
'query': 'ratio >= 0 && ratio < 1', | |
'column': 'ratio' | |
}, | |
'backgroundColor': 'green', | |
'color': 'white' | |
} | |
} | |
# Sample target searches in data dictionary | |
list(find_target_in_nested_dictionary(data, 'if')) # target is nested key | |
list(find_target_in_nested_dictionary(data, 'green')) # target is nested value | |
list(find_target_in_nested_dictionary(data, 'ratio')) # target in nested value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment