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

如何将字典列表转换为含嵌套字典的目标字典列表?

字典列表格式转换问题解决

原代码存在的问题

  • 字段映射错误:构造pickupAddress时,把latitude赋值给了zipcode,把zipcode赋值给了latitude,完全搞反了对应关系
  • 实现方式冗余:用列表存元组再转字典的方式绕了弯路,直接构造字典更简洁高效
  • 结构拼接错误:把pickupAddress和deliveryAddress分别存到两个列表,没有合并成每个元素包含两个地址的目标字典结构
  • 多余判断:循环里的if i < len(x)毫无意义,因为循环本身就是按输入列表长度遍历的

正确实现代码

直接遍历输入列表中的每个字典,按要求构造嵌套字典即可:

def transform_addresses(x):
    y = []
    for item in x:
        # 构造取件地址字典
        pickup_addr = {
            "zipcode": item["zipcode"],
            "latitude": item["latitude"],
            "longitude": item["longitude"]
        }
        # 构造配送地址字典
        delivery_addr = {
            "zipcode": item["delivery_zip"],
            "latitude": item["delivery_lat"],
            "longitude": item["delivery_lng"]
        }
        # 组合成目标字典并加入结果列表
        y.append({
            "pickupAddress": pickup_addr,
            "deliveryAddress": delivery_addr
        })
    return y

验证示例

输入:

x = [{'delivery_zip': '12432',
  'delivery_lat': 42.0437,
  'delivery_lng': -73.9474,
  'distance': 43.81927669168279,
  'latitude': 41.6770047,
  'longitude': -73.7535413,
  'zipcode': 12510},
 {'delivery_zip': '12404',
  'delivery_lat': 41.8293989,
  'delivery_lng': -74.2414092,
  'distance': 43.872670571109516,
  'latitude': 41.6770047,
  'longitude': -73.7535413,
  'zipcode': 12510}]

调用函数后得到的输出和期望完全一致:

y = transform_addresses(x)
print(y)
# 输出:
# [{'pickupAddress': {'zipcode': 12510, 'latitude': 41.6770047, 'longitude': -73.7535413}, 'deliveryAddress': {'zipcode': '12432', 'latitude': 42.0437, 'longitude': -73.9474}}, {'pickupAddress': {'zipcode': 12510, 'latitude': 41.6770047, 'longitude': -73.7535413}, 'deliveryAddress': {'zipcode': '12404', 'latitude': 41.8293989, 'longitude': -74.2414092}}]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:55:20