如何遍历Header字典值并构建符合指定结构的嵌套字典?
问题需求与修改建议
需求说明
需要遍历Header字典中的值(而非键)实现以下逻辑:
- 从
SubkeyList中取出元素,同时获取Header的主键(如dtc_all); - 遍历
Header字典的值(如udsDtcValue),将Main_Key、Sub_Key、Element作为参数传入get_value_nested_dict函数获取对应值; - 构建新字典,将获取到的值更新到对应位置,同时保持
Header中的键顺序; - 对
SubkeyList中的每个元素重复上述操作,按顺序将结果加入新字典。
当前代码的问题是遍历了Header字典的键,而非值,需要调整实现逻辑。
相关数据与当前代码
嵌套源字典
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']
当前实现代码
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
预期输出
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'} } } }
修改后的实现建议
要实现遍历Header的值(即内层字段名,如udsDtcValue),需要嵌套遍历Header的层级:先遍历Header['dtc_all']的键值对,再遍历每个值的键(目标字段)。Python 3.7+默认字典保持插入顺序,无需额外处理。
修改后的代码如下:
def create_new_dict(Nested_Dict, Header, SubkeyList): new_dict = {'dtc_all': {}} main_key = 'dtc_all' for sub_key in SubkeyList: sub_item_dict = {} # 遍历Header中dtc_all的顶层键(如DiagnosticTroubleCodeUds)及其字段字典 for top_key, fields in Header[main_key].items(): field_dict = {} # 遍历顶层键下的字段(即Header的值,如udsDtcValue) for field in fields.keys(): field_value = get_value_nested_dict(Nested_Dict, main_key, sub_key, field) if field_value: field_dict[field] = field_value[0] sub_item_dict[top_key] = field_dict new_dict[main_key][sub_key] = sub_item_dict return new_dict
说明
- 外层先构建匹配预期输出的顶层结构
{'dtc_all': {}}; - 嵌套遍历
Header[main_key]的每个顶层键,再遍历该键对应字典的所有字段(需求中要遍历的Header的值); - 对每个字段调用
get_value_nested_dict获取值,构建字段字典后添加到对应顶层键下; - 最后将每个
sub_key对应的完整字典加入到new_dict[main_key]中,保持顺序。
内容的提问来源于Stack Exchange,提问作者shekhar sabale
相关产品推荐
相关产品推荐

