Last active
February 19, 2021 10:57
-
-
Save elinaldosoft/1ab3fbf2ebd9e04e7067f4e184ab0de6 to your computer and use it in GitHub Desktop.
Filter dict is a method for search element in depth
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
In [1]: def filter_dict(data: dict, extract): | |
...: try: | |
...: if isinstance(extract, list): | |
...: for i in extract: | |
...: result = filter_dict(data, i) | |
...: if result: | |
...: return result | |
...: keys = extract.split('.') | |
...: shadow_data = data.copy() | |
...: for key in keys: | |
...: if str(key).isnumeric(): | |
...: key = int(key) | |
...: shadow_data = shadow_data[key] | |
...: return shadow_data | |
...: except IndexError: | |
...: return None | |
...: | |
In [2]: data = {'data': {'customer': {'name': 'Luke', 'phones': [{'type': 'mobile', 'number': '11999997777'}, {'type': 'home', 'number': '11999998888'}]}}} | |
In [3]: filter_dict(data, 'data.customer.name') | |
Out[3]: 'Luke' | |
In [4]: filter_dict(data, 'data.customer.phones') | |
Out[4]: | |
[{'type': 'mobile', 'number': '11999997777'}, | |
{'type': 'home', 'number': '11999998888'}] | |
In [5]: filter_dict(data, 'data.customer.phones.0') | |
Out[5]: {'type': 'mobile', 'number': '11999997777'} | |
In [6]: filter_dict(data, 'data.customer.phones.1') | |
Out[6]: {'type': 'home', 'number': '11999998888'} | |
In [7]: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment