python附加到所有词典

时间:2017-11-16 19:36:49

标签: python list pandas dictionary append

我在词典中使用了dictoinaries。循环遍历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中所有字典中的所有百分比相同。为什么呢?

2 个答案:

答案 0 :(得分:2)

sheetstats[action] = general_form 

基本上是在每个键槽中放置相同的字典,您可以将其视为指向general_form的每个键

您可以做的是复制general_form

for action in action_types:
    sheetstats[action] = dict(general_form)

复制数据结构的正确方法是使用模块copy及其deepcopy函数,它将复制深层结构(例如类):

import copy
for action in action_types:
    sheetstats[action] = copy.deepcopy(general_form)

答案 1 :(得分:0)

您将在每次迭代时分配general_form。

您是否想要从action_types中分配值?

sheetstats [action] = action_types [action]?

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] = action_types[action]

    #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)