Skip to content

Instantly share code, notes, and snippets.

@sairoko12
Created Dec 22, 2018
Embed
What would you like to do?
Utils functions for python projects
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