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

Python中字典子集化:从d1和d2生成目标字典d3

如何从字典d1和d2生成目标字典d3?

可以用字典推导式快速实现需求,核心逻辑就是遍历d1的所有键,判断是否存在于d2中,存在则按索引取值,不存在则直接保留原键值对:

d1 = {'criterion': 0, 'other':1, 'n_estimators': 240}
d2 = {'criterion': ["gini", "entropy", "log_loss"], 'other': ["sqrt", "log2"]}

d3 = {k: d2[k][v] if k in d2 else v for k, v in d1.items()}
print(d3)
# 输出: {'criterion': 'gini', 'other': 'log2', 'n_estimators': 240}

逻辑说明:

  • 遍历d1的每一组键值对(k, v)
  • 如果键k同时存在于d2中,就用d1里的v作为索引,取出d2中对应列表的元素
  • 如果键k只在d1里有,直接保留原有的值v

注:你提供的示例中d3的other值写的是"entropy",但按规则d2['other'][1]对应的应该是"log2",上述代码会生成符合逻辑的正确结果。

如果需要更直观的循环写法(适合新手理解),也可以这样写:

d3 = {}
for k, v in d1.items():
    if k in d2:
        d3[k] = d2[k][v]
    else:
        d3[k] = v

两种写法都能满足你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 03:20:27