You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python合并嵌套字典指定键值并调整Outcomes结构的实现方法

实现代码
import pandas as pd
import numpy as np

# 原始Outcomes字典
Outcomes = {
    'Values':{
        'First': {
            'option 1': np.array([12,345,5412]),
            'option 2': np.array([2315,32,1]),
            'option 4': {'row 4': np.array([232,3,1]),
                         'row 5': np.array([3,4,5]),
                         'row 6': np.array([15,6,12])}
        },
        'Second': {
            'option 1': np.array([1,4,5]),
            'option 2': np.array([5,6,3]),
            'option 3': {'row 1': np.array([-5,3,1]),
                         'row 2': np.array([4,4,12]),
                         'row 3': np.array([67,6,5])}        
    }
}
Concatinating_variables = ['option 3', 'option 4']

# 取出两个待拼接的内容
opt3 = Outcomes['Values']['Second'][Concatinating_variables[0]]
opt4 = Outcomes['Values']['First'][Concatinating_variables[1]]

# 按option3在前、option4在后的顺序合并字典(Python3.7及以上默认保留键顺序)
merged_opt = {**opt3, **opt4}

# 替换原option4内容
Outcomes['Values']['First'][Concatinating_variables[1]] = merged_opt

# 删除不需要的Second层级,匹配预期结构
del Outcomes['Values']['Second']

如果使用Python3.7以下版本,字典无法保证顺序,替换合并步骤为以下代码即可:

from collections import OrderedDict
merged_opt = OrderedDict(list(opt3.items()) + list(opt4.items()))

内容的提问来源于stack exchange,提问作者bull selcuk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 05:06:03