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

如何在Python中从列表字典提取值以创建新字典?

解决方法

首先明确:你想要的第一个new_dict在Python里无法实现——字典的键必须唯一,重复的键会被最后一个值覆盖,实际运行后只会得到{'FRUITS': 'PECAN'}。所以合理的实现目标是第二个形式,把同一键对应的值存成集合或列表。

方法一:普通循环构建

old_list_dict = [{'A':'FRUITS','B':'APPLE'}, {'A':'FRUITS','B':'BANANA'}, {'A':'FRUITS','B':'PECAN'}]

new_dict = {}
for item in old_list_dict:
    key = item['A']
    value = item['B']
    if key not in new_dict:
        new_dict[key] = set()  # 用集合自动去重,要保留顺序就换成列表[]
    new_dict[key].add(value)  # 用列表的话改成append(value)

print(new_dict)
# 输出: {'FRUITS': {'APPLE', 'BANANA', 'PECAN'}}

方法二:用collections.defaultdict简化代码

如果想让代码更简洁,可借助标准库的defaultdict:

from collections import defaultdict

old_list_dict = [{'A':'FRUITS','B':'APPLE'}, {'A':'FRUITS','B':'BANANA'}, {'A':'FRUITS','B':'PECAN'}]

new_dict = defaultdict(set)
for item in old_list_dict:
    new_dict[item['A']].add(item['B'])

# 如需转成普通字典,执行dict(new_dict)即可
print(dict(new_dict))
# 输出: {'FRUITS': {'APPLE', 'BANANA', 'PECAN'}}

补充:值为列表(保留原始顺序)

如果不需要去重,想保留元素的原始顺序,把集合换成列表就行:

old_list_dict = [{'A':'FRUITS','B':'APPLE'}, {'A':'FRUITS','B':'BANANA'}, {'A':'FRUITS','B':'PECAN'}]

new_dict = {}
for item in old_list_dict:
    key = item['A']
    value = item['B']
    if key not in new_dict:
        new_dict[key] = []
    new_dict[key].append(value)

print(new_dict)
# 输出: {'FRUITS': ['APPLE', 'BANANA', 'PECAN']}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 10:30:01