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

如何按zone与cycle键对List of Dictionary中的字典进行分组?

按zone和cycle组合分组字典列表的解决方案

看起来你需要把字典列表里,zone和cycle键值完全匹配的字典归到同一个子列表中,这里有两种实用的Python实现方法,帮你搞定这个需求:

方法一:手动用字典分组(直观易理解)

这种方法不需要导入额外模块,通过一个中间字典来存储分组结果,逻辑清晰,适合新手理解:

d = [{'count': '100', 'zone': 'PIMPRI', 'cycle': '15'}, 
     {'count': '50', 'zone': 'PIMPRI', 'cycle': '15'}, 
     {'count': '150', 'zone': 'PIMPRI', 'cycle': '30'}]

# 初始化分组字典,键用(zone, cycle)的元组(元组可哈希,能当字典键)
group_dict = {}
for item in d:
    # 生成当前字典的分组标识
    group_key = (item['zone'], item['cycle'])
    # 如果这个分组还不存在,就创建一个空列表
    if group_key not in group_dict:
        group_dict[group_key] = []
    # 把当前字典加入对应分组的列表
    group_dict[group_key].append(item)

# 提取所有分组的子列表,得到最终结果
grouped_result = list(group_dict.values())
# 按需赋值给变量
d_one, d_two = grouped_result

print(d_one)
# 输出:[{'count': '100', 'zone': 'PIMPRI', 'cycle': '15'}, {'count': '50', 'zone': 'PIMPRI', 'cycle': '15'}]
print(d_two)
# 输出:[{'count': '150', 'zone': 'PIMPRI', 'cycle': '30'}]

方法二:使用itertools.groupby(简洁高效)

如果你的数据量较大,或者喜欢更简洁的代码,可以用Python标准库的itertools.groupby,不过要注意先按分组键排序,因为groupby只会对连续的相同元素分组:

from itertools import groupby

d = [{'count': '100', 'zone': 'PIMPRI', 'cycle': '15'}, 
     {'count': '50', 'zone': 'PIMPRI', 'cycle': '15'}, 
     {'count': '150', 'zone': 'PIMPRI', 'cycle': '30'}]

# 先按zone和cycle排序,确保相同组合的字典连续排列
sorted_d = sorted(d, key=lambda x: (x['zone'], x['cycle']))

# 按(zone, cycle)分组,把每组转成列表存入结果
grouped_result = []
for _, group_items in groupby(sorted_d, key=lambda x: (x['zone'], x['cycle'])):
    grouped_result.append(list(group_items))

# 按需赋值变量
d_one, d_two = grouped_result

print(d_one)
print(d_two)

两种方法都能完美实现你的需求,你可以根据自己的习惯和场景选择~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:31:54