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

如何根据用户输入更新Python中的字典列表?

解决方案

我们可以分两步完成需求:先解析用户输入的字符串,再更新字典列表。

步骤1:解析用户输入

把用户输入的字符串转换成可操作的键值对:

user_input = "Pepsi: 3.0, Sprite: 2.50"
# 分割成单个饮料-价格条目
entries = user_input.split(',')
# 处理每个条目,整理成字典
update_dict = {}
for entry in entries:
    # 去除前后空格后按冒号分割
    drink, price_str = entry.strip().split(':')
    # 将价格转换为浮点数,存入字典
    update_dict[drink.strip()] = float(price_str.strip())

步骤2:更新字典列表

遍历解析后的键值对,检查原列表中是否存在对应饮料:存在则更新价格,不存在则添加新字典:

drinks_info = [{'Pepsi': 2.0}, {'Coke': 2.0}, {'Solo': 2.50}, {'Mt Dew': 3.0}]

for drink, new_price in update_dict.items():
    found = False
    for item in drinks_info:
        if drink in item:
            # 更新已有饮料的价格
            item[drink] = new_price
            found = True
            break
    if not found:
        # 添加新的饮料条目
        drinks_info.append({drink: new_price})

print(drinks_info)

运行后输出结果如下:

[{'Pepsi': 3.0}, {'Coke': 2.0}, {'Solo': 2.50}, {'Mt Dew': 3.0}, {'Sprite': 2.50}]

优化小技巧

如果你的字典列表条目较多,逐个遍历的效率会偏低。可以先将原列表转换为普通字典,更新后再转回字典列表,代码更简洁且效率更高:

# 将原列表转换为普通字典
temp_dict = {}
for item in drinks_info:
    temp_dict.update(item)
# 批量更新价格
temp_dict.update(update_dict)
# 转回字典列表格式
drinks_info = [{k: v} for k, v in temp_dict.items()]

内容的提问来源于stack exchange,提问作者Thomas.L

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 07:15:32