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

元组列表转字典时如何保留所有含重复键的条目?

处理含重复键的元组列表转字典的问题

当你有如下元组列表:

points = [(1, 2), (1, 5), (2, 5), (3, 3), (3, 7), (6, 5), (9, 9)]

直接使用dict()转换为字典时:

dictionary = dict(points)

会得到丢失部分条目的结果:

{1: 5, 2: 5, 3: 7, 6: 5, 9: 9}

其中(1,2)和(3,3)这两个条目被移除了。

原因说明

这是因为Python字典不允许存在重复键,转换过程中后出现的同键值对会直接覆盖之前的条目。

解决方案

如果需要保留所有同键对应的数值,可以借助collections.defaultdict,将每个键对应的值存储为列表:

from collections import defaultdict
result = defaultdict(list)
for key, value in points:
    result[key].append(value)

转换后的字典结构为:

{1: [2,5], 2: [5], 3: [3,7], 6: [5], 9: [9]}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 00:20:51