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

推荐答案

好多了,好多了.🤓

您需要确保对于Header字典 struct 的每一部分,我们不仅要迭代键,还要进入它们的嵌套 struct ,从Nested_Dict检索udsDtcValueFaultTypedescriptionfailure_name.

def get_value_from_nested_dict(nested_dict, path):
    for key in path:
        nested_dict = nested_dict.get(key, {})
        if not nested_dict:
            return None
    return nested_dict
def create_new_dict(nested_dict, header, subkey_list):
    new_dict = {'dtc_all': {}}
    path_mappings = {'DiagnosticTroubleCodeUds': ['identification'], 'dtcProps': ['identification'], 'DiagnosticTroubleCodeObd': ['functional_conditions']}
    for sub_key in subkey_list:
        sub_dict_structure = {}
        for header_key, inner_keys in header['dtc_all'].items():
            header_sub_dict = {}
            for inner_key in inner_keys.keys():
                base_path = ['candela_samples_generic', 'drc_dtcs', 'dtc_all', sub_key]
                specific_path = path_mappings.get(header_key, [])
                value_path = base_path + specific_path + [inner_key]
                value = get_value_from_nested_dict(nested_dict, value_path)
                if value is not None:
                    header_sub_dict[inner_key] = value
            if header_sub_dict:
                sub_dict_structure[header_key] = header_sub_dict
        if sub_dict_structure:
            new_dict['dtc_all'][sub_key] = sub_dict_structure
    return new_dict
        

Python相关问答推荐

使用scipy. optimate.least_squares()用可变数量的参数匹配两条曲线

当多个值具有相同模式时返回空

PywinAuto在Windows 11上引发了Memory错误,但在Windows 10上未引发

如何列举Pandigital Prime Set

在Mac上安装ipython

梯度下降:简化要素集的运行时间比原始要素集长

从一个系列创建一个Dataframe,特别是如何重命名其中的列(例如:使用NAs/NaN)

实现自定义QWidgets作为QTimeEdit的弹出窗口

无法在Docker内部运行Python的Matlab SDK模块,但本地没有问题

在单次扫描中创建列表

以逻辑方式获取自己的pyproject.toml依赖项

(Python/Pandas)基于列中非缺失值的子集DataFrame

如何合并具有相同元素的 torch 矩阵的行?

当HTTP 201响应包含 Big Data 的POST请求时,应该是什么?  

你能把函数的返回类型用作其他地方的类型吗?'

为什么后跟inplace方法的`.rename(Columns={';b';:';b';},Copy=False)`没有更新原始数据帧?

如何获取包含`try`外部堆栈的`__traceback__`属性的异常

将字节序列解码为Unicode字符串

删除另一个div中的特定div容器

PYODBC错误(SQL包含-26272个参数标记,但提供了235872个参数,HY 000)