Created
June 30, 2022 07:54
-
-
Save Stefano314/9cb2e6d4fa396601eca272494364dc30 to your computer and use it in GitHub Desktop.
Create the union of a generic list of dictionaries.
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 flatten_list(lst : list) -> list: | |
""" | |
Description | |
----------- | |
Flatten an irregular list of lists (meaning that it can contain also non lists). If there are multiple nested lists | |
the function must be used as many times as the nested order. | |
""" | |
result = [] | |
if isinstance(lst, list): | |
for i in lst: | |
if isinstance(i, list): | |
for j in i: | |
result.append(j) | |
else: | |
result.append(i) | |
else: | |
result.append(lst) | |
return result | |
def union_dictionary(ds : list) -> dict: | |
""" | |
Description | |
----------- | |
Create the union of a list of dictionaries. | |
""" | |
merged = dict() | |
for d in ds: | |
try: | |
for key in d.keys(): | |
if key not in merged.keys(): | |
merged[key] = [] | |
merged[key].append(flatten_list(d[key])) | |
merged[key] = flatten_list(merged[key]) | |
except: | |
print('VALUE ERROR: Zero size dictionary given.') | |
return merged | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment