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

如何将用户输入列表作为字典值追加?Python代码覆写问题修复

问题:Python字典分类存储产品时的覆写问题

我编写了一段Python代码,用于将用户输入的产品信息按分类存储到字典中,但代码未实现追加功能,反而出现覆写问题,导致每个分类下的产品都是重复的同一个值。

原代码

def store(s_name,loc):
    cat = []
    products = {}
    for i in range(1,h+1):
        a = input(f"Enter category {i}: ").title()
        cat.append(a)
    for x in cat:
        p = int(input(f"How many products are available in category {x}: "))
        for j in range(p):
            product_nm = input("Enter product name: ").title()
            products[x] = [product_nm]
            products[x].append(product_nm)
    p = f"*****************************************************************
Store Name is {s_name}
Store Location: {loc}
Categories Available: {cat}
Variety Includes: {products}"
    return p
s_name = input("Enter name of your store: ").upper()
loc = input("Enter city of your store: ").title()
h = int(input("How many categories are available: "))
z = store(s_name,loc)
print(z)

当前错误输出

Variety Includes: {'Electronics': ['Smartphone', 'Smartphone'], 'Electricals': ['Air Conditioner', 'Air Conditioner']}

期望正确输出

Variety Includes: {'Electronics': ['Smartphone', 'Computer'], 'Electricals': ['Air Conditioner', 'Refrigerator']}

问题分析

关键错误出在这段代码:

products[x] = [product_nm]
products[x].append(product_nm)

每次循环输入产品时,都会先将products[x]重新赋值为仅包含当前产品的列表,随后又追加同一个产品名,导致两个问题:

  1. 同分类下之前输入的产品被完全覆写
  2. 最终列表里是重复的同一个产品名

修复方案

有两种简洁的修改方式,均可实现产品的追加存储:

方式一:提前初始化分类列表

在处理每个分类的产品前,先为该分类创建一个空列表,后续直接向列表中追加产品即可:

def store(s_name,loc):
    cat = []
    products = {}
    for i in range(1,h+1):
        a = input(f"Enter category {i}: ").title()
        cat.append(a)
    for x in cat:
        p = int(input(f"How many products are available in category {x}: "))
        # 提前初始化当前分类的空列表
        products[x] = []
        for j in range(p):
            product_nm = input("Enter product name: ").title()
            # 直接追加产品到列表
            products[x].append(product_nm)
    # 修正f-string的换行语法,避免报错
    p = f"*****************************************************************\nStore Name is {s_name}\nStore Location: {loc}\nCategories Available: {cat}\nVariety Includes: {products}"
    return p
s_name = input("Enter name of your store: ").upper()
loc = input("Enter city of your store: ").title()
h = int(input("How many categories are available: "))
z = store(s_name,loc)
print(z)

方式二:使用dict.setdefault动态初始化

如果不想提前初始化列表,可使用setdefault方法——当分类键不存在时自动创建空列表,存在则直接返回已有列表,再执行追加操作:

def store(s_name,loc):
    cat = []
    products = {}
    for i in range(1,h+1):
        a = input(f"Enter category {i}: ").title()
        cat.append(a)
    for x in cat:
        p = int(input(f"How many products are available in category {x}: "))
        for j in range(p):
            product_nm = input("Enter product name: ").title()
            # 用setdefault确保列表存在,再追加产品
            products.setdefault(x, []).append(product_nm)
    # 修正f-string的换行语法,避免报错
    p = f"*****************************************************************\nStore Name is {s_name}\nStore Location: {loc}\nCategories Available: {cat}\nVariety Includes: {products}"
    return p
s_name = input("Enter name of your store: ").upper()
loc = input("Enter city of your store: ").title()
h = int(input("How many categories are available: "))
z = store(s_name,loc)
print(z)

注:原代码的f-string未添加换行符\n会导致语法错误,上述修复代码已同步修正该问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:09:24