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

Python:如何以Pythonic方式重映射字典列表键名(拼接对应索引前缀)

如何用Pythonic的方式重映射字典列表中每个字典的键名?

问题描述

需要将字典列表中每个字典的键名重映射为「对应索引的列表值-原键简化名」的格式,示例如下:

输入字典列表:

[
    [{'Capture & Acquis.': '', 'Storage & Accounting': 'X', 'Transformation': ''}],
    [{'Process': 'Acquisition', 'Report': 'Final'}],
    [{'Responsible': 'APE', 'Department': 'ACC'}]
]

待添加名称列表:

['Dataflow', 'Scope', 'Owner']

期望输出:

[
    [{'Dataflow-Capture': '', 'Dataflow-Storage': 'X', 'Dataflow-Transformation': ''}],
    [{'Scope-Process': 'Acquisition', 'Scope-Report': 'Final'}],
    [{'Owner-Responsible': 'APE', 'Owner-Department': 'ACC'}]
]

Pythonic 解法

利用列表推导式、字典推导式和zip()函数可以简洁实现需求,代码如下:

# 输入数据
dict_list = [
    [{'Capture & Acquis.': '', 'Storage & Accounting': 'X', 'Transformation': ''}],
    [{'Process': 'Acquisition', 'Report': 'Final'}],
    [{'Responsible': 'APE', 'Department': 'ACC'}]
]
names = ['Dataflow', 'Scope', 'Owner']

# 重映射键名
result = [
    [
        {f"{name}-{key.split()[0]}": val for key, val in d.items()}
        for d in sublist
    ]
    for sublist, name in zip(dict_list, names)
]

# 查看结果
print(result)

代码说明

  1. zip()配对:将字典列表的每个子列表和名称列表的对应元素一一配对,确保每个子列表能拿到正确的前缀名称。
  2. 嵌套推导式:外层遍历配对后的子列表与名称,内层遍历子列表中的每个字典,用字典推导式生成新字典。
  3. 键名处理:对原键使用split()[0]提取第一个单词(处理示例中带特殊字符的长键名),再通过f-string拼接前缀名称与简化后的键名,值保持原字典的对应值不变。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 05:55:16