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

如何在字典列表中合并两个键的值并赋值给新键?

合并字典列表中指定键的值到新键

没问题,这事儿用Python处理起来很直观,咱们直接遍历字典列表,把指定字段的值拼接后赋值给新键就行。

核心解法

先修正个小细节:你的fields列表里写的是"Fuel_Type",但示例字典里的实际键是"Fuel",我就按示例里的真实键来写代码啦。

fields = ["Classification", "Fuel"]
target = "Classification_Fuel_Type"
d = [
    {
        "Fuel": "Gas",
        "Gears": 6,
        "Width": 209,
        "Year": 2012,
        "Engine": "Lincoln 5.4L 8 Cylinder 310 hp 365 ft-lbs FFV",
        "Classification": "Automatic transmission",
    },
    {
        "Fuel": "E85",
        "Gears": 5,
        "Width": 209,
        "Year": 2014,
        "Engine": "Lincoln 5.4L 8 Cylinder 310 hp 365 ft-lbs FFV",
        "Classification": "Automatic transmission",
    },
    {
        "Fuel": "E85",
        "Gears": 6,
        "Width": 509,
        "Year": 2011,
        "Engine": "Lincoln 5.4L 8 Cylinder 310 hp 365 ft-lbs FFV",
        "Classification": "Automatic transmission",
    },
]

# 遍历每个字典完成合并操作
for item in d:
    # 拼接指定字段的值,这里用空字符串直接连接,需要分隔符的话换成' '即可
    combined_val = ''.join([item[field] for field in fields])
    # 给新键赋值
    item[target] = combined_val

代码说明

  • 循环遍历列表里的每一个字典item;
  • 用列表推导式取出fields中指定的两个键对应的值,再通过str.join()把它们拼接起来;
  • 最后把拼接结果赋值给目标键target。

可选:处理异常情况

如果担心某些字典可能缺少指定的键,怕抛出KeyError,可以用dict.get()方法兜底,默认返回空字符串:

combined_val = ''.join([item.get(field, '') for field in fields])

最终结果

运行上面的代码后,你的字典列表就会变成你期望的样子:

[
    {
        "Classification_Fuel_Type": "Automatic transmissionGas",
        "Fuel": "Gas",
        "Gears": 6,
        "Width": 209,
        "Year": 2012,
        "Engine": "Lincoln 5.4L 8 Cylinder 310 hp 365 ft-lbs FFV",
        "Classification": "Automatic transmission",
    },
    {
        "Classification_Fuel_Type": "Automatic transmissionE85",
        "Fuel": "E85",
        "Gears": 5,
        "Width": 209,
        "Year": 2014,
        "Engine": "Lincoln 5.4L 8 Cylinder 310 hp 365 ft-lbs FFV",
        "Classification": "Automatic transmission",
    },
    {
        "Classification_Fuel_Type": "Automatic transmissionE85",
        "Fuel": "E85",
        "Gears": 6,
        "Width": 509,
        "Year": 2011,
        "Engine": "Lincoln 5.4L 8 Cylinder 310 hp 365 ft-lbs FFV",
        "Classification": "Automatic transmission",
    },
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:14:26