简体   繁体   中英

Python - Insert value to list in a dictionary

I need your help to fix my code. I try to append a value to a list in a dictionary.

def distance(x1, y1, x2, y2):
  dis=((x1-x2)**2) + ((y1-y2)**2)
  return dis

def cluster_member_formation2(arrCH, arrN, k):
  dicCH = dict.fromkeys(arrCH,[])
  arrE = []
  for j in range(len(arrCH)):
    d_nya = distance(arrN[1][0], arrN[1][1], arrN[arrCH[j]][0], arrN[arrCH[j]][1])
    arrE.append(d_nya)
  minC = min(arrE)
  ind = arrE.index(minC)
  x = arrCH[ind]
  dicCH[x].append(1)
  print(arrE, minC, ind, x, dicCH)

arrCH=[23, 35]
arrN={0:[23, 45, 2, 0], 1:[30,21,2,0], 23:[12, 16, 2, 0], 35:[48, 77, 2, 0]}

cluster_member_formation2(arrCH, arrN, 1)

The output:

[349, 3460] 349 0 23 {35: [1], 23: [1]}

I try to calculate the distance between node 1 and all node in arrCH, and then take the minimum distance. In the output show the result of arrE is [349, 3460], so the minimum is 349. 349 has index 0, then I find arrCH with index 0, likes arrCH[0]=23. Finally, I want update dicCH[23].append(1) so the result is

{35: [], 23: [1]}

But, why my code update the all keys, 35 and 23?

I hope someone can help me. Thank you..

classmethod fromkeys(seq[, value])

Create a new dictionary with keys from seq and values set to value .

All of your dictionary values reference the same single list instance ( [] ) which you provide as a value to the fromkeys function.

You could use dictionary comprehension as seen in this answer .

dicCH = {key: [] for key in arrCH}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM