我是使用 Python 2.75 的新程序员
我有一个by_sale
以这种格式调用的嵌套字典:
{sale : {days_elapsed: daily_sales_amount}}.
例如:
{'Spring Savings 0413' : {1 : 3000, 2: 2000, 4:1000},
'Back to School 0812' : {1: 4000, 3:3000, 4:2000}}
请注意,“春季储蓄 0413”没有第 3 天,“返校 0812”没有第 2 天。
我试图创建一个名为的新字典by_day
,它将存储每天和每次销售的总金额,即使是没有新销售的日子,如下所示:
{1: {'Spring Savings 0413': 3000, 'Back to School 0812': 4000},
2: {'Spring Savings 0413': 5000, 'Back to School 0812': 4000},
3: {'Spring Savings 0413': 5000, 'Back to School 0812': 7000},
4: {'Spring Savings 0413': 6000, 'Back to School 0812': 9000}}
这是我的代码:
by_day = {}
for sale in by_sale.iterkeys():
running_total = 0
for i in range(1,4): #check for each day in the first 4 days
by_day[i] = {} #initialize a nested blank dictionary for each day
daily_amount = by_sale[sale].get(i,0) #grab the amount for the day, if none, return a zero
running_total += daily_amount
by_day[i][sale] = running # --> I know this is my problem... but why?
print by_day
我得到的只是最后一次销售的值,这似乎覆盖了其他销售数据:
{1: {'Back to School 0812': 4000},
2: {'Back to School 0812': 4000},
3: {'Back to School 0812': 7000},
4: {'Back to School 0812': 9000}}
我有点明白这里发生了什么......我只是不知道如何阻止它发生。任何指针将不胜感激!