Created
June 24, 2022 18:55
-
-
Save titovanton/164443a6e2c4fba4565a31f5178d64be to your computer and use it in GitHub Desktop.
This file contains hidden or 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 to_dict(table, *keys, **kwargs): | |
""" | |
Coverts table like 2D list to dict | |
Args: | |
table (list of dict): result of values_list ORM method, | |
lets interpret each dict item of the list as a `row`. | |
*keys: keys in order from highest to lowest dimension | |
kwargs[flat_val_from] (str): if provided - returns flat key -> atomic dict, | |
other wise returns key -> `row`. | |
kwargs[condition] (func): function of 1 parameter - `row`, | |
which returns True/False | |
Returns: | |
dict | |
""" | |
assert len(table) | |
assert type(table[0]) is dict | |
assert len(keys) | |
output = {} | |
flat_val_from = kwargs.get('flat_val_from') | |
condition = kwargs.get('condition') | |
NO_VALUE = '%1%2%3#4# no value #5#6@7*8@9&^' | |
for row in table: | |
if condition and not condition(row): | |
continue | |
prev_tmp = tmp = output | |
for key in keys: | |
row_value = row.get(key, NO_VALUE) | |
if row_value == NO_VALUE: | |
break | |
prev_tmp = tmp | |
tmp = tmp.setdefault(row_value, {}) | |
if row_value == NO_VALUE: | |
continue | |
if flat_val_from: | |
prev_tmp[row_value] = row[flat_val_from] | |
else: | |
tmp.update(row) | |
return output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment