I'm trying to transform a dictionaries of list and nested dictionaries into a cleaner list of dictionaries but testing one of the nested values.
Basically from this:
my_dict = {
'N': [
{'DATE': 2019, 'VALUE': 1},
{'DATE': 2018, 'VALUE': 2}
],
'LT': [
{'DATE': 2019, 'VALUE': 40},
{'DATE': 2001, 'VALUE': 50}
]
}
to this:
my_dict_transformed = [
{'DATE': 2019, 'N': 1, 'LT': 40},
{'DATE': 2018, 'N': 2, 'LT': 'NULL'},
{'DATE': 2001, 'N': 'NULL', 'LT': 50}
]
Thanks to all the solutions proposed. I think @Rakesh solution is the cleanest. While having a default function like @Anurag suggested could be very useful with a slightly different data structure.
This is one approach.
Ex:
my_dict = {
'N': [
{'DATE': 2019, 'VALUE': 1},
{'DATE': 2018, 'VALUE': 2}
],
'LT': [
{'DATE': 2019, 'VALUE': 40},
{'DATE': 2001, 'VALUE': 50}
]
}
my_dict_transformed = {}
for k, v in my_dict.items():
for i in v:
if i["DATE"] not in my_dict_transformed:
my_dict_transformed[i["DATE"]] = {'DATE': i["DATE"]}
my_dict_transformed[i["DATE"]].update(dict((i,"NULL") for i in my_dict.keys()))
my_dict_transformed[i["DATE"]][k] = i.pop('VALUE')
print(list(my_dict_transformed.values()))
Output:
[{'DATE': 2001, 'LT': 50},
{'DATE': 2018, 'N': 2},
{'DATE': 2019, 'LT': 40, 'N': 1}]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments