Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Converion of dictionary to list of tuples (Stackoverflow problem)
import json def get_filtered_data(data_list, parent): # print(data_list, parent) if not data_list: return [] l = [] for d in data_list: parents = [] texts = [] if not parent: parents.append(None) # Python has None for Null values , JavaScript has null, C/C++ have NULL else: parents.append(parent) texts.append(d['text']) # print(zip(parents, texts)) l = l + list(zip(parents, texts)) + get_filtered_data(d['children'], parent + 1) return l # Starting point if __name__ == "__main__": parent = 0 # Input Data data = [ { 'text':'first_layer 1', 'children':[ { 'text':'second_layer 11', 'children':[ { 'text':'third_layer 111', 'children': [], } ], }, { 'text':'second_layer 12', 'children':[] } ], } ] output_list = get_filtered_data(data, parent) print(output_list, '\n') # In each tuple, 1st item is parent id, 2nd one is text of current child element # [(None, 'first_layer 1'), (1, 'second_layer 11'), (2, 'third_layer 111'), (1, 'second_layer 12')] # Sorting based on parent id output_list2 = sorted(output_list, key=lambda tup: 0 if tup[0] is None else tup[0]) print(output_list2, '\n') # [(None, 'first_layer 1'), (1, 'second_layer 11'), (1, 'second_layer 12'), (2, 'third_layer 111')] output_list3 = [(index + 1,) + tup for index, tup in enumerate(output_list2)] print(output_list3, '\n') # [(1, None, 'first_layer 1'), (2, 1, 'second_layer 11'), (3, 2, 'third_layer 111'), (4, 1, 'second_layer 12')] pretty_output = json.dumps(output_list3, indent=4) print(pretty_output) """ [ [ 1, null, "first_layer 1" ], [ 2, 1, "second_layer 11" ], [ 3, 1, "second_layer 12" ], [ 4, 2, "third_layer 111" ] ] """
run
|
edit
|
history
|
help
0
PyTempConvDIP
lab00.py
Test
Hesap makinesi
gj2
sai hw
PyLSV
π―π―π―π―π―π―π―π½Guess the number π½π―π―π―π―π―π―π―
Prime Numbers : -> Conventional Method
Python Monthly Calendar