Nested_Dict =
{'candela_samples_generic': {'drc_dtcs': {'domain_name': 'TEMPLATE-DOMAIN', 'dtc_all':{
'0x930001': {'identification': {'udsDtcValue': '0x9300', 'FaultType': '0x11', 'description': 'GNSS antenna short to ground'},
'functional_conditions': {'failure_name': 'short_to_ground', 'mnemonic': 'DTC_GNSS_Antenna_Short_to_ground'}},
'0x212021': {'identification': {'udsDtcValue': '0x2120', 'FaultType': '0x21', 'description': 'ECU internal Failure'},
'functional_conditions': {'failure_name': 'short_to_ground', 'mnemonic': 'DTC_GNSS_Antenna_Short_to_ground'}}}}}}
Header = {
'dtc_all': {
'DiagnosticTroubleCodeUds': {'udsDtcValue': None, 'FaultType': None},
'dtcProps': {'description': None},
'DiagnosticTroubleCodeObd': {'failure_name': None}
}
}
SubkeyList = ['0x930001','0x212021']
Expected Output:
New_Dict=
{'dtc_all':
{'0x930001': {'DiagnosticTroubleCodeUds': {'udsDtcValue': '0x9300', 'FaultType': '0x11'}, 'dtcProps':{'description': 'GNSS antenna short to ground'}, 'DiagnosticTroubleCodeObd': {'failure_name':short_to_ground}}},
{'0x212021': {'DiagnosticTroubleCodeUds': {'udsDtcValue': '0x2120', 'FaultType': '0x21'}, 'dtcProps':{'description': 'ECU internal Failure'}, 'DiagnosticTroubleCodeObd': {'failure_name':short_to_ground}}}}
参考问题:Aggregating Inputs into a Consolidated Dictionary
这里想在头字典内迭代头字典的值,但用我的代码,它迭代的是dict的键,而不是dict的值. 从SubkeyList中取一个元素,从字典中取一个头键(可以有多个头键,比如dtc_all).在头字典中迭代字典的值,例如'udsDtcValue'.
For example:
Main_Key = dtc_all
Sub_Key = 0x212021
Element = udsDtcValue
将这些参数传递给函数get_value_nested_dict(nested_dict,Main_Key,Sub_Key,Element).这个函数将返回元素的值.get_value_nested_dict func,它与我发布的元素值检索预期一样工作.同时,创建一个新字典,并在正确的位置更新元素值,例如'udsDtcValue':'0x9300 '.此外,确保键的序列与标头中的相同.类似地,在头字典内遍历字典的所有值,如FaultType、Description,直到failure_name.对SubkeyList中的每个元素重复这些迭代,并以相同的顺序将结果附加到new_dict中.有什么建议吗?
def create_new_dict(Nested_Dict, Header, SubkeyList):
new_dict = {}
for sub_key in SubkeyList:
sub_dict = {}
for element, value in Header['dtc_all'].items():
value = get_value_nested_dict(Nested_Dict, 'dtc_all', sub_key, element)
if value:
sub_dict[element] = value[0]
new_dict[sub_key] = sub_dict
return new_dict