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

Python字典键值对添加异常:重复键致数据丢失问题求助

问题原因及解决方法

问题根源

Python字典的键具有唯一性,你的代码中用「元素重复次数」作为字典的键,当多个元素的重复次数相同时(比如cherry、potato、tomato的次数都是1),后续的键值对会直接覆盖之前的。遍历sorted(list(set(my_list)))时,TOMATO是最后一个被处理的,所以键1最终对应的值就只剩TOMATO,其他同次数的元素都被覆盖掉了。

修正方案

根据需求,有两种合理的处理方式:

方案1:交换键值(推荐,符合字典设计逻辑)

把元素作为键,重复次数作为值,这样每个元素对应唯一的计数,不会出现覆盖问题:

my_list = ["apple", "cherry", "apple", "potato", "tomato", "apple"]
my_grocery = {}
while True:
    try:
        prompt = input().upper().strip()
        my_list.append(prompt)
    except EOFError:
        # 手动统计次数
        for item in my_list:
            if item in my_grocery:
                my_grocery[item] += 1
            else:
                my_grocery[item] = 1
        # 也可以用collections.Counter简化代码:
        # from collections import Counter
        # my_grocery = Counter(my_list)
        print(my_grocery)
        break

输出示例:

{'APPLE': 3, 'CHERRY': 1, 'POTATO': 1, 'TOMATO': 1}

方案2:以次数为键,值用列表存储同次数元素

如果一定要保留「次数为键」的结构,可以把同次数的元素放到列表中,避免覆盖:

my_list = ["apple", "cherry", "apple", "potato", "tomato", "apple"]
my_grocery = {}
while True:
    try:
        prompt = input().upper().strip()
        my_list.append(prompt)
    except EOFError:
        my_list_unique = sorted(list(set(my_list)))
        for item in my_list_unique:
            count = my_list.count(item)
            # 若键不存在,先创建空列表
            if count not in my_grocery:
                my_grocery[count] = []
            my_grocery[count].append(item)
        print(my_grocery)
        break

输出示例:

{3: ['APPLE'], 1: ['CHERRY', 'POTATO', 'TOMATO']}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 21:22:40