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

如何根据State_Index为字典列表的子字典添加State_Name字段

问题描述

我有如下格式的字典列表:

input = [{'Clause':'Text that describes clause 1', 'Source':'pdf_file', 'additional_info': {'State_Index':0, 'City_Index':0, 'Population':100}},
        {'Clause':'Text that describes clause 2', 'Source':'pdf_file', 'additional_info': {'State_Index':0, 'City_Index':1, 'Population':150}},
        {'Clause':'Text that describes clause 3', 'Source':'pdf_file', 'additional_info': {'State_Index':1, 'City_Index':0, 'Population':75}},
        {'Clause':'Text that describes clause 4', 'Source':'pdf_file', 'additional_info': {'State_Index':1, 'City_Index':1, 'Population':20}}]

每个字典包含Clause、Source字段,以及存储州/市索引等信息的additional_info子字典。另有State_Index与State_Name的对应表:

State_IndexState_Name
0AL
1AK
......
49WY

需要为每个additional_info字典添加对应的State_Name字段,求实现方法。


解决方案

步骤1:将州索引-名称对应表转为字典

先把州对应关系转换成Python字典,这样能通过索引快速查找州名,效率最高:

state_mapping = {
    0: 'AL',
    1: 'AK',
    # 补充剩余48个州的索引-名称对应关系
    49: 'WY'
}

步骤2:遍历列表添加字段

循环遍历每个条目,从additional_info中取出State_Index,通过映射字典获取州名后添加到子字典中:

for item in input:
    state_index = item['additional_info']['State_Index']
    # 用get方法避免索引不存在时报错,可指定默认值
    state_name = state_mapping.get(state_index, 'Unknown')
    item['additional_info']['State_Name'] = state_name

验证结果

执行后,input中每个additional_info都会新增State_Name字段,例如第一个条目会变为:

{'Clause':'Text that describes clause 1', 
 'Source':'pdf_file', 
 'additional_info': {'State_Index':0, 'City_Index':0, 'Population':100, 'State_Name': 'AL'}}

可选优化:批量处理简化写法

如果数据量较大,可使用列表推导式简化代码(效果与循环一致):

input = [
    {**item, 'additional_info': {**item['additional_info'], 'State_Name': state_mapping.get(item['additional_info']['State_Index'], 'Unknown')}}
    for item in input
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 20:02:08