如何将字典列表中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
相关产品推荐
相关产品推荐

