python-3.xlistdictionaryoptimizationswarm

Custom class using nested dictionary Python


I have a problem when adding value inside the nested dictionary using the same keys and the value is always shown the same value, The fact is, i want update the value event the keys is same. This algorithm is the basic of Artificial Fish Swarm Algorithm

# example >> fish_template = {0:{'weight':3.1,'visual':2,'step':1},1:'weight':3,'visual':4,'step':2}}

fish = {}
fish_value = {}
weight = [3.1, 3, 4.1, 10]
visual = [2, 4, 10, 3]
step = [1, 2, 5, 1.5]

len_fish = 4

for i in range(0,len_fish):
  for w, v, s in zip(weight, visual, step):
     fish_value["weight"] = w
     fish_value["visual"] = v
     fish_value["step"] = s
     fish[i] = fish_value

  print("show fish",fish)

I expect the result to be like fish_template, but it isn't. The values for the keys 'weight', 'visual', 'step' are always the same with values of 0, 1, 2, and 3. Any solution?


Solution

  • The issue is with fish[i], you simply created a dict with the same element: fish_value. Python does not generate a new memory for the same variable name, so all your dict keys point to the same value=fish_value, which gets overwritten and all your dict values take the last state of fish_value. To overcome this, you can do the following:

    fish   = {}
    weight = [3.1, 3, 4.1, 10]
    visual = [2, 4, 10, 3]
    step   = [1, 2, 5, 1.5]
    
    len_fish = 4
    
    for i in range(0, len_fish):
         fish[i]= {"weight": weight[i], "visual": visual[i], "step": step[i]}
    
    print("show fish", fish)
    
    

    As @Error mentioned, the for loop can be replaced by this one-liner:

    fish = dict((i, {"weight": weight[i], "visual": visual[i], "step": step[i]}) for i in range(len_fish))