Last active
July 3, 2021 17:37
-
-
Save AnkDos/8ba7fb6a2af8c42c8fab3615b1398595 to your computer and use it in GitHub Desktop.
Method to Parse any type of dictionary in python without using recursion . Input any dict , Returns list of list of all key value pair in dict
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 dictionary_parser(dict_): | |
""" | |
Traversing through any type of dictionary wihout using recursion | |
Input any dict , Returns list of list of all key value pair in dict | |
SAMPLE : | |
:arg : { | |
"a": "b", | |
"c": "d", | |
"e": [ | |
{"aa": "bb"}, | |
{"aa": "dd"} | |
] | |
} | |
:returns [['a', 'b'], ['c', 'd'], ['e', [{'aa': 'bb'}, {'aa': 'dd'}]], ['aa', 'bb'], ['aa', 'dd']] | |
""" | |
if not isinstance(dict_, dict): | |
raise Exception("Input should be a dictionary") | |
hold = [] | |
for key, value in dict_.items(): | |
if isinstance(value, dict) or isinstance(value, list): | |
hold.append([key, value, False]) | |
else: | |
hold.append([key, value, True]) | |
for index, values in enumerate(hold): | |
key, value, processed = values | |
if not processed: | |
if isinstance(value, dict): | |
for keys, val in value.items(): | |
hold.append([keys, val, False]) | |
elif isinstance(value, list): | |
for data in value: | |
if isinstance(data, dict): | |
for list_keys, list_val in data.items(): | |
hold.append([list_keys, list_val, False]) | |
else: | |
hold.append([key, value, True]) | |
hold[index] = [key, value, True] | |
if shall_break(hold): | |
break | |
new_list = [] | |
for key, val, processed in hold: | |
if [key, val] not in new_list: | |
new_list.append([key, val]) | |
return new_list | |
def shall_break(val): | |
"""""" | |
for key, value, proccessed in val: | |
if not proccessed: | |
return False | |
return True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment