【问题标题】:python appends to all dictionariespython附加到所有字典
【发布时间】: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


【解决方案1】:
sheetstats[action] = general_form 

基本上就是在每个key slot里放了同一个字典,你可以把这想成是每个key都指向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)

【讨论】:

    【解决方案2】:

    您在每次迭代中分配 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)
    

    【讨论】:

      猜你喜欢
      • 2016-12-30
      • 2012-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-07
      • 2015-08-22
      • 2020-10-14
      • 1970-01-01
      相关资源
      最近更新 更多