因此,我尝试以这种格式解析传入的字典:
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":[]}
]
}
但是到目前为止,我仅设法对每个key:-dict-lists
进行了转换,现在我需要根据转换后的字典输出将这些键合并。我想做的事情如下。
这是我当前的字典:
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)
问题来源:stackoverflow
这是一种使用带有dict.setdefault`的嵌套迭代的方法。
例如:
result = {}
for _, v in initial_dict.items():
for i in v:
for k, sv in i.items():
if k not in result:
result[k] = {}
if sv:
for values in sv:
for m, n in values.items():
result[k].setdefault(m, []).append(n)
print(result)
输出:
{'fault': {'fault_code': [888, 333, 222, 549],
'fault_external_code': [111, 101, 222, 202]},
'ff': {'heater': [220, 55, 170, 80],
'radiator': [20.34, 10.33, 6.4, 10.9],
'temperature': [33, 44, 18, 67]}}
回答来源:stackoverflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。