【发布时间】:2019-08-23 21:47:58
【问题描述】:
我正在尝试创建一个嵌套字典,其中包含一组从 for 循环中提取的值,以衡量各种客户-产品配对的增长和收入金额。但是,当我遍历数据框以设置字典的元素时,每个字典元素最终都具有相同的值。这是怎么回事?
我已经尝试过更改列表构建方式的各种元素,但无济于事。
'''
TP_Name = customer name
Service_Level_1 = service name
100.2014 is just a marker to show that someone has started consuming the service
tpdict is already created with necessary nesting below with empty values at each endpoint
'''
for col in pivotdf.columns:
growthlist = []
amountlist = []
first = True
TP_Name, Service_Level_1 = col.split('___')
for row in pivotdf[col]:
if first == True:
past = row+.00001
first = False
if row == 0 and past <.0001 :
growth = 0
elif row != 0 and past == .00001:
growth = 100.2014
else:
current = row
growth = (current-past)/past
growth = round(growth,4)
growthlist.append(growth)
past = row +.00001
amountlist.append(row)
tpdict[TP_Name][Service_Level_1]['growth'] = growthlist
tpdict[TP_Name][Service_Level_1]['amount'] = amountlist
'''
problem: Each value ends up being the same thing
'''
Expected results:
{'CUSTOMER NAME': {'PRODUCT1': {'growth': [unique_growthlist], 'amount': [unique_amountlist]}, 'PRODUCT2': {'growth': [unique_growthlist],'amount': [unique_amountlist]}}}
【问题讨论】:
-
在您的预期结果中,您有两个具有相同值的键,键需要是唯一的
-
字典是一个键值对(我相信你知道)。如果您尝试使用已存在的键写入字典,它将覆盖该值。
-
@Error - 语法悔恨,这些键具有唯一值,这些值在
TP_Name, Service_Level_1 = col.split('___')行中的“for-loop”中更改。 @depperm - 预期的结果,每个名称和产品都有唯一的名称,这只是一个示例。将进行修改以使其更加清晰。 -
尝试复制列表:
tpdict[TP_Name][Service_Level_1]['growth'] = list(growthlist)否则dict指向的对象是不断被修改的对象 -
@enixon4 是
pivotdf一个实际的pandas.DataFrame因为看起来你可以通过一些聚合操作来做你正在做的事情,然后to_dict()它......
标签: python list dictionary for-loop iteration