【发布时间】:2018-04-30 11:15:28
【问题描述】:
我在字典中使用字典。循环遍历 pandas 数据帧,操作行的值始终与字典中的一个键匹配,并且基于该行中的一些其他值被附加到该字典中的列表中。但是,出于某种原因,这些值会附加到其他字典中的所有列表中
general_form = {
"Percentage": np.nan, "DayPercentage": np.nan, "sample_size": np.nan, "Percentages": [], "DayPercentages": []
}
#get all possible action types
action_types = self.df['Action Type'].tolist()
action_types = list(set(action_types))
#give every action type its own dictionary within the main dictionary
sheetstats = {}
for action in action_types:
sheetstats[action] = general_form
#push the percentage in the list inside the dictionary specified in
#action
for index, row in self.df.iterrows():
percentage = row['Percentage']
daypercentage = row['DayPercentage']
action = row['Action Type']
sheetstats[action]['Percentages'].append(percentage)
sheetstats[action]["DayPercentages"].append(daypercentage)
这将使 sheetstats 内的所有字典中的所有百分比都相同。为什么?
【问题讨论】:
-
因为你使用的是同一个字典:
sheetstats[action] = general_form. -
sheetstats[action] = general_form是说你想在每个键槽中放同一个字典...我想你想复制general_form
标签: python list pandas dictionary append