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

如何将含字符串与字典的元组列表按相同键分组?

实现相同键对应值的分组转换

这里有几种实用的方法可以完成你需要的数据转换,以下是具体实现:

方法1:普通字典手动分组

适合基础场景,无需引入额外模块:

input_data = [
    ('key1', {'a': 'b'}), 
    ('key2', {'w': 'x'}), 
    ('key1', {'c': 'd'}), 
    ('key2', {'y': 'z'})
]

result_dict = {}
for key, val in input_data:
    # 若键不存在则初始化空列表
    if key not in result_dict:
        result_dict[key] = []
    result_dict[key].append(val)

# 转换为目标列表元组格式
result = list(result_dict.items())

方法2:使用collections.defaultdict(推荐)

借助标准库工具简化代码,无需手动判断键是否存在:

from collections import defaultdict

input_data = [
    ('key1', {'a': 'b'}), 
    ('key2', {'w': 'x'}), 
    ('key1', {'c': 'd'}), 
    ('key2', {'y': 'z'})
]

# 默认值为列表的字典
result_dict = defaultdict(list)
for key, val in input_data:
    result_dict[key].append(val)

# 转换为目标格式
result = list(result_dict.items())

方法3:使用itertools.groupby

注意:使用该方法必须先按key排序,因为groupby仅对连续的相同键进行分组:

from itertools import groupby

input_data = [
    ('key1', {'a': 'b'}), 
    ('key2', {'w': 'x'}), 
    ('key1', {'c': 'd'}), 
    ('key2', {'y': 'z'})
]

# 先按键排序,确保同键元素连续
sorted_data = sorted(input_data, key=lambda x: x[0])
# 分组并提取对应的值列表
result = [(key, [item[1] for item in group]) for key, group in groupby(sorted_data, key=lambda x: x[0])]

验证遍历逻辑

以上三种方法得到的result都可以按你需要的方式遍历:

for t in result:
    for val in t[1]:
        print(val)

输出结果:

{'a': 'b'}
{'c': 'd'}
{'w': 'x'}
{'y': 'z'}

内容的提问来源于stack exchange,提问作者H. Senkaya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 05:06:42