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

使用Collections.Counter统计重复字典,同时保留对应priority键值对

嘿,我来帮你搞定这个需求!要实现用Counter统计重复字典,同时保留对应的priority,其实分几步就能搞定,我给你两种常见场景的解决方案哈:

解决方案

情况1:原始数据是带type键的字典列表

如果你的原始数据是类似[{'type': 'MPLS', 'priority': 1}, ...]这种格式,直接按下面的步骤来:

代码示例

from collections import Counter

# 模拟你的原始数据(实际替换成你自己的列表)
original_data = [
    {'type': 'MPLS', 'priority': 1},
    {'type': 'MPLS', 'priority': 1},
    {'type': 'MPLS', 'priority': 1},
    {'type': 'Down', 'priority': 10},
    {'type': 'Down', 'priority': 10},
    {'type': '4G', 'priority': 3},
    {'type': 'DSL', 'priority': 2}
]

# 1. 先建立「类型-priority」的映射(确保同一类型对应唯一priority)
type_priority_map = {item['type']: item['priority'] for item in original_data}

# 2. 用Counter统计每个类型的出现次数
type_counts = Counter(item['type'] for item in original_data)

# 3. 生成你要的目标格式列表
result = [
    {'type': typ, 'count': cnt, 'priority': type_priority_map[typ]}
    for typ, cnt in type_counts.items()
]

print(result)

代码解释

  • 第一步的字典推导式会自动帮你把每个类型对应的priority存起来,只要同一类型的priority一致,不管重复多少次都能正确映射。
  • 第二步用Counter统计类型出现次数,这里通过生成器表达式提取每个字典的type字段,高效又简洁。
  • 最后用列表推导式把三者组合成你要的字典结构,直接得到目标结果。

情况2:原始数据是类型作为键的字典列表

如果你的原始数据是类似[{'MPLS': 'xxx', 'priority': 1}, ...]这种格式(每个字典除了priority只有一个类型键),可以这样处理:

代码示例

from collections import Counter

# 模拟你的原始数据
original_data = [
    {'MPLS': 'value1', 'priority': 1},
    {'MPLS': 'value2', 'priority': 1},
    {'Down': 'value3', 'priority': 10},
    {'Down': 'value4', 'priority': 10},
    {'4G': 'value5', 'priority': 3},
    {'DSL': 'value6', 'priority': 2}
]

type_priority_map = {}
type_list = []

# 遍历原始数据,提取类型和对应的priority
for item in original_data:
    # 取出当前字典中除了'priority'之外的键(也就是类型)
    typ = next(k for k in item if k != 'priority')
    type_list.append(typ)
    type_priority_map[typ] = item['priority']

# 统计类型出现次数
type_counts = Counter(type_list)

# 生成第一种格式的结果(类型作为键)
result_format1 = [
    {typ: cnt, 'priority': type_priority_map[typ]}
    for typ, cnt in type_counts.items()
]

# 生成第二种格式的结果(统一用type/count键)
result_format2 = [
    {'type': typ, 'count': cnt, 'priority': type_priority_map[typ]}
    for typ, cnt in type_counts.items()
]

print("格式1结果:", result_format1)
print("格式2结果:", result_format2)

代码解释

  • 这里用next(k for k in item if k != 'priority')来提取每个字典里的类型键,因为假设每个字典只有一个类型键,所以这个方法能快速拿到。
  • 剩下的步骤和第一种情况类似,统计次数后组合成你需要的两种格式之一就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:34:31