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

遍历嵌套字典计算剩余库存:避免KeyError的实现方案

解决库存剩余量计算及KeyError规避问题

Hey there, let's work through this inventory calculation problem together. The core challenges here are handling mismatched date keys, avoiding annoying KeyErrors, and tracking individual vessel outbound records instead of just aggregating sales totals. Here's a straightforward, robust approach:

Approach Breakdown

  1. Cover all inventory dates: We need to include every date present in the inventory data, even if there's no corresponding sales demand for it.
  2. Preserve original data: Start with a copy of the current inventory for each date to avoid modifying the source data.
  3. Safe key access: Use Python's dictionary get() method to safely retrieve values—this returns a default (like 0) if the key doesn't exist, eliminating KeyErrors.
  4. Track vessel-specific outbound: Maintain a separate dictionary to log exactly how much each vessel took from each grade on each date.

Solution Code

# Provided inventory and sales data
inventory = {
    '2020-02-28': {'ASF': 220102, 'MFA': 100109, 'PRE': 218256},
    '2020-03-29': {'ASF': 321200, 'MFA': 151505, 'PRE': 175000},
    '2020-03-01': {'ASF': 312765, 'MFA': 300021, 'PRE': 118561},
    '2020-03-02': {'ASF': 121203, 'MFA': 209909, 'PRE': 210000}
}

sales = {
    '2020-02-28': {
        'CEYLON': {'ASF': 55000, 'MFA': 0, 'PRE': 0},
        'PACIFIC MAJOR': {'ASF': 100000, 'MFA': 0, 'PRE': 0},
        'CCSC YASA JING': {'ASF': 10000, 'MFA': 6000, 'PRE': 18000}
    },
    '2020-03-01': {
        'ABC': {'ASF': 0, 'MFA': 0, 'PRE': 65000},
        'DEF etc': {'ASF': 0, 'MFA': 19191, 'PRE': 0}
    },
    '2020-03-02': {
        'ABC': {'ASF': 75000, 'MFA': 10000, 'PRE': 0},
        'DEF etc': {'ASF': 55000, 'MFA': 55000, 'PRE': 0}
    }
}

# Initialize result storage
remaining_inventory = {}
vessel_outbound_records = {}

# Get all dates from inventory (includes dates with no sales)
all_dates = inventory.keys()

for date in all_dates:
    # Start with a copy of the current inventory to avoid modifying original data
    remaining_inventory[date] = inventory[date].copy()
    # Set up empty outbound records for the date
    vessel_outbound_records[date] = {}
    
    # Safely get sales data for the date (empty dict if no sales exist)
    daily_sales = sales.get(date, {})
    
    for vessel, vessel_demand in daily_sales.items():
        # Initialize record for this vessel
        vessel_outbound_records[date][vessel] = {}
        for grade in inventory[date].keys():
            # Get demand for the grade (0 if not specified in sales)
            demand = vessel_demand.get(grade, 0)
            # Update remaining inventory
            remaining_inventory[date][grade] -= demand
            # Log the outbound quantity for the vessel
            vessel_outbound_records[date][vessel][grade] = demand

# Example output verification
print("=== Remaining Inventory ===")
for date, grades in remaining_inventory.items():
    print(f"{date}: {grades}")

print("\n=== Vessel Outbound Records ===")
for date, vessels in vessel_outbound_records.items():
    print(f"\n{date}:")
    for vessel, grades in vessels.items():
        print(f"  {vessel}: {grades}")

Key Notes

  • No KeyErrors: sales.get(date, {}) ensures dates without sales data just use an empty dict, so the inner vessel loop skips gracefully. vessel_demand.get(grade, 0) handles missing grade entries in vessel demand.
  • Original data preserved: Using inventory[date].copy() means we don't alter the source inventory dictionary.
  • Full outbound tracking: The vessel_outbound_records dict keeps a complete log of every vessel's activity, so you can audit exactly what was taken when.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 22:47:57