Python供需价格板开发:如何用字典数值更新另一字典键值?
伪供需价格板开发解决方案
问题背景
开发Python期末作业伪供需价格板,需实现以下需求:
- 基于
metalDict中动态变化的金属基础成本,通过公式更新outputDict内各城市的价格 - 使用Numpy和Pandas完成最终表格输出
当前代码定义
金属基础成本字典
metalDict = { 'Iron Ingot': 1, 'Copper Ingot':10, 'Tin Ingot':30, 'Silver Ingot':100, 'Gold Ingot':1000, 'Mithral Ingot':5000}
结果输出字典
outputDict = { "metals" : ['Iron Ingots', 'Copper Ingots', 'Tin Ingots', 'Silver Ingots', 'Gold Ingots', 'mithral Ingots'], "wholesale" : [metalDict['Iron Ingot'], metalDict['Copper Ingot'],metalDict['Tin Ingot'],metalDict['Silver Ingot'], metalDict['Gold Ingot'], metalDict['Mithral Ingot']], 'city 1' : [1,2,3,4,5,6], 'city 2' : [1,2,3,4,5,6], 'city 3' : [1,2,3,4,5,6], 'city 4' : [1,2,3,4,5,6], 'city 5' : [1,2,3,4,5,6]}
现有尝试的问题
尝试的代码触发KeyError: 'city 1',错误代码如下:
city1Needs = np.random.randint (2, size=100) city1Demand = 40 if city1Demand <= 40: for key, value in outputDict.items(): if key == 'city 1': Outputdict['city 1'] = (metalDict[key]/2) + metalDict[key]
错误原因:
- 拼写错误:
Outputdict应为outputDict - 逻辑错误:用
city 1作为键去取metalDict的值,但metalDict中无此键,需对应金属名称匹配计算
可行解决方案
方案1:基于现有字典改进
先统一金属名称的一致性(解决单复数、大小写问题),再通过索引对应计算城市价格:
# 统一金属名称,与metalDict完全匹配 outputDict["metals"] = ['Iron Ingot', 'Copper Ingot', 'Tin Ingot', 'Silver Ingot', 'Gold Ingot', 'Mithral Ingot'] # 动态更新批发价(metalDict变化时可复用) outputDict["wholesale"] = [metalDict[metal] for metal in outputDict["metals"]] # 定义各城市价格系数(可根据需求动态调整) city_coeffs = { 'city 1': 1.5, 'city 2': 1.6, 'city 3': 1.4, 'city 4': 1.7, 'city 5': 1.3 } # 批量更新所有城市价格 for city, coeff in city_coeffs.items(): outputDict[city] = [metalDict[metal] * coeff for metal in outputDict["metals"]] # 示例:单独更新city1(加入需求逻辑) city1Demand = 40 if city1Demand <= 40: outputDict['city 1'] = [metalDict[metal] * 1.5 for metal in outputDict["metals"]]
方案2:使用Pandas(推荐,适配表格输出)
利用Pandas的DataFrame天然适配表格结构,简化索引对应和动态更新:
import pandas as pd import numpy as np # 从metalDict直接初始化DataFrame df = pd.DataFrame({ 'metals': list(metalDict.keys()), 'wholesale': list(metalDict.values()) }) # 定义城市价格系数 city_coeffs = { 'city 1': 1.5, 'city 2': 1.6, 'city 3': 1.4, 'city 4': 1.7, 'city 5': 1.3 } # 批量生成城市价格列 for city, coeff in city_coeffs.items(): df[city] = df['wholesale'] * coeff # 动态更新函数(适配metalDict变化和需求调整) def update_prices(df, metalDict, demand_dict=None): # 更新批发价 df['wholesale'] = [metalDict[metal] for metal in df['metals']] # 根据需求调整价格 for city in city_coeffs.keys(): coeff = city_coeffs[city] if demand_dict and city in demand_dict: demand = demand_dict[city] # 需求高于50时涨价20% if demand > 50: coeff *= 1.2 df[city] = df['wholesale'] * coeff # 示例:模拟metalDict动态变化和城市需求 metalDict['Iron Ingot'] = 2 demand_dict = {'city 1': 60, 'city 2': 30} update_prices(df, metalDict, demand_dict) # 输出指定列(符合预期表格格式) print(df[['wholesale', 'city 1']])
Pandas方案优势:
- 自动维护金属与价格的对应关系,避免索引错误
- 动态更新逻辑更简洁,易扩展供需相关规则
- 内置表格格式化、统计等功能,适配期末作业展示需求
内容的提问来源于stack exchange,提问作者MacAndWeenies
相关产品推荐
相关产品推荐

