Итак, я пытаюсь проанализировать входящий словарь в следующем формате:
initial_dict = {
"row_index_1":[
{"ff":[{"temperature":33, "radiator":20.34, "heater":220},
{"temperature":44, "radiator":10.33, "heater":55}]},
{"fault":[]}
],
"row_index_2":[
{"ff":[]},
{"fault":[{"fault_code":888, "fault_external_code":111},
{"fault_code":333, "fault_external_code":101}]}
],
"row_index_3":[
{"ff":[]},
{"fault":[{"fault_code":222, "fault_external_code":222},
{"fault_code":549, "fault_external_code":202}]}
],
"row_index_4":[
{"ff":[{"temperature":18, "radiator":6.40, "heater":170},
{"temperature":67, "radiator":10.90, "heater":80}]},
{"fault":[]}
]
}
Но пока мне удалось преобразовать только per key:list-of-dicts
, и теперь мне нужно объединить их на основе этих ключей на этом преобразованном словарном выводе. То, что я пытаюсь сделать, выглядит примерно так:
Это мой текущий дикт:
current_dict = {'row_index_1': {'temperature': [33, 44],'radiator': [20.34, 10.33], 'heater': [220, 55]},
'row_index_2': {'fault_external_code': [111, 101], 'fault_code': [888, 333]},
'row_index_3': {'fault_external_code': [111, 202], 'fault_code': [222, 459]},
'row_index_4': {'temperature': [18,67],'radiator': [6.40, 10.90], 'heater': [170, 80]}}
Мой желаемый вывод:
desired_dict = {'ff': {'temperature': [33, 44, 18, 67],
'radiator': [20.34, 10.33, 6.40, 10.90],
'heater': [220, 55, 170, 80]},
'fault': {'fault_external_code': [111, 101, 111, 202],
'fault_code': [888, 333, 222, 459]}
Мне удалось получить current_dict
со следующими функциями:
import operator
from functools import reduce
def dict_comprehension_flatten(input_list):
"""
#TODO
"""
all_keys = reduce(operator.or_, (d.keys() for d in input_list))
print(all_keys)
print(input_list)
output_dict = {key: [d.get(key) for d in input_list] for key in all_keys}
return output_dict
def convert_dict(input_dict, list_of_keys):
"""
#TODO
"""
output_dict = {}
for row_index in input_dict.keys():
for elem in input_json[row_index]:
if list(elem.values())[0] != []:
output_dict[row_index] = dict_comprehension_flatten(list(elem.values())[0])
return output_dict
dict_keys = ['ff', 'fault']
current_dict = convert_dict(initial_dict, dict_keys)