gpt4 book ai didi

python - 如何在不覆盖的情况下将键/值对插入嵌套字典中?

转载 作者:太空宇宙 更新时间:2023-11-03 11:06:31 26 4
gpt4 key购买 nike

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

请注意“ Spring 储蓄 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

我得到的只是最后一次销售的值(value),它似乎覆盖了其他销售数据:

{1: {'Back to School 0812': 4000}, 
2: {'Back to School 0812': 4000},
3: {'Back to School 0812': 7000},
4: {'Back to School 0812': 9000}}

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

最佳答案

这是没有 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}}

关于python - 如何在不覆盖的情况下将键/值对插入嵌套字典中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17932126/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com