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

如何将字典列表中key值转为新键、type值转为对应新值?

问题描述

现有字典列表:

file = [{'key': 'apple', 'type':'fruit'},
        {'key': 'beans', 'type':'vegetable'},
        {'key': 'beans', 'type':'fruit'}]

期望输出满足:

  • 将key字段的值作为新字典的键
  • 将type字段的值作为新字典对应的值

预期输出:

{'apple': 'fruit', 'beans':['vegetable','fruit']}

当前使用代码:

super_dict = {}
for d in file:
    for l, m in d.items():  
        super_dict.setdefault(l, []).append(m)
super_dict

实际输出:

{'key': ['apple', 'beans', 'beans'], 'type': ['fruit', 'vegetable', 'fruit']}

请求修正代码以得到预期输出。

修正方案

核心是直接提取每个字典里的key和type值,而非遍历所有键值对,同时根据键的重复情况处理对应值的格式:

super_dict = {}
for d in file:
    current_key = d['key']
    current_type = d['type']
    if current_key in super_dict:
        # 键已存在,处理值的格式
        if isinstance(super_dict[current_key], list):
            super_dict[current_key].append(current_type)
        else:
            # 单个值转成列表后追加新值
            super_dict[current_key] = [super_dict[current_key], current_type]
    else:
        # 键不存在,直接赋值
        super_dict[current_key] = current_type

运行后得到预期输出:

{'apple': 'fruit', 'beans': ['vegetable', 'fruit']}

代码说明

  • 直接遍历原列表中的每个字典,取出目标字段key和type的值,避免无效的键值对遍历
  • 针对键的存在情况做分支处理:
    • 首次出现的键直接将type值作为对应value
    • 重复出现的键,若当前value是单个值则转为列表,再追加新的type值;若已是列表则直接追加

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:25:21