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','0x240001']
从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中. 有什么建议吗?
输出:New_Dict应该是这样的:
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}}}}
def get_value_nested_dict(nested_dict, main_key, sub_key, element):
results = []
def search_for_element(sub_dict, looking_for_element):
if isinstance(sub_dict, dict):
for k, v in sub_dict.items():
if k == element and looking_for_element:
results.append(v)
else:
search_for_element(v, looking_for_element)
def search_nested_dict(current_dict):
if isinstance(current_dict, dict):
for key, value in current_dict.items():
if key == main_key:
if sub_key in value:
search_for_element(value[sub_key], True)
else:
search_for_element(value, False)
else:
search_nested_dict(value)
search_nested_dict(nested_dict)
return results