Created
December 22, 2018 05:06
-
-
Save sairoko12/66aa2e1f9d9ca4374cc14435edfb9fcd to your computer and use it in GitHub Desktop.
Utils functions for python projects
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
def dict_to_list(dictionary): | |
return [ | |
[ | |
key, | |
dict_to_list(value) if isinstance(value, (dict)) else value | |
] for key, value in dictionary.items() | |
] | |
def first_value_of_matrix(matrix): | |
value = None | |
for item in matrix: | |
if isinstance(item, (list)): | |
return first_value_of_matrix(item) | |
else: | |
value = item | |
break | |
return value | |
def is_list(value): | |
return isinstance(value, (list)) | |
def is_dict(value): | |
return isinstance(value, (dict)) | |
def navigate_into_dict(dot_path, dictionary): | |
if not dot_path or not dictionary: | |
return None | |
parts_of_path = dot_path.split('.') | |
for index, key in enumerate(parts_of_path): | |
if key.isnumeric() and is_list(dictionary): | |
try: | |
return dictionary[int(key)] | |
except IndexError: | |
return None | |
elif key in dictionary.keys() and is_dict(dictionary[key]) or is_list(dictionary[key]): | |
del parts_of_path[index] | |
if len(parts_of_path) == 0: | |
return dictionary[key] | |
else: | |
return navigate_into_dict(".".join(parts_of_path), dictionary[key]) | |
else: | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment