4

我是使用 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}}

我有点明白这里发生了什么......我只是不知道如何阻止它发生。任何指针将不胜感激!

4

2 回答 2

2

这是没有的解决方案defaultdict

d = {'Spring Savings 0413' : {1 : 3000, 2: 2000, 4:1000}, 
 'Back to School 0812' : {1: 4000, 3:3000, 4:2000}}

r = {}

for s, l in d.items():
    for i in range(1, 5):
        if i not in r: r[i] = {}
        r[i][s] = l.get(i, 0) + r.get(i - 1, {}).get(s, 0)

{1: {'Back to School 0812': 4000, 'Spring Savings 0413': 3000},
 2: {'Back to School 0812': 4000, 'Spring Savings 0413': 5000},
 3: {'Back to School 0812': 7000, 'Spring Savings 0413': 5000},
 4: {'Back to School 0812': 9000, 'Spring Savings 0413': 6000}}
于 2013-07-29T19:30:27.447 回答
1

您正在使用覆盖每个循环上每个键的条目by_day[i] = {}。您应该检查是否存在密钥,在这种情况下,您应该更新现有的字典。

或者,使用集合。defaultdict

>>> by_sale = {'Spring Savings 0413' : {1 : 3000, 2: 2000, 4:1000}, 'Back to School 0812' : {1: 4000, 3:3000, 4:2000}}
>>> 
>>> 
>>> from collections import defaultdict
>>> 
>>> by_day = defaultdict(dict)
>>> for sale, sale_info in by_sale.iteritems():
...     running_total = 0
...     for i in range(1,5):
...         daily_amount = sale_info.get(i,0)
...         running_total += daily_amount
...         by_day[i].update({sale:running_total})
... 
>>> 
>>> dict(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}}

你应该range(1, 5)改用。range(1, 4)给出 - [1, 2, 3]

于 2013-07-29T19:09:00.043 回答