e.g. a=[[3,789],[1,100],[1,102],[2,102],[1,106],[2,456]]; Convert to a dictionary b={1:[100,102,102],2:[102,456],3:[789]}
If cast is used:
1 >>> a=[[3,789],[1,100],[1,102],[2,102],[1,106],[2,456]]; 2 >>> b=dict (a)3 >>> b4 {1:106, 2:456, 3:789} 5
The result obviously removes the value corresponding to the duplicate key in the dictionary;
1 #Convert a list to a dictionary2 deflisttodict ():3a=[[3,789],[1,100],[1,102],[2,102],[1,106],[2,456]];4Lenarr=Len (a);5 #lists all element values in the first column, including repeating elements6Firstcol=[];7 forIinchRange (Lenarr):8Firstcol.append (A[i][0]);#[3, 1, 1, 2, 1, 2]9 #List all the non-repeating elements in the first columnTenFirstcolnotrep=set (Firstcol);#the elements in the {-i} collection do not have order OneFirstcolnotrep=list (FIRSTCOLNOTREP);#firstcolnotrep=[1,2,3] A #count the number of non-repeating elements in the first column -lenfirstcolnotrep=Len (firstcolnotrep); -B=[];c=[]; the forIinchRange (lenfirstcolnotrep): -B.append ([firstcolnotrep[i]]);#[ 1], [2], [3]] - forIinchRange (lenfirstcolnotrep): - forJinchRange (Lenarr): + ifFIRSTCOLNOTREP[I]==A[J][0]:#firstcolnotrep=[1,2,3] - Print(j); +B[i].append (a[j][1]); A returnb; at #results b=[[1,100,102,106],[2,102,456], [3,789]] - - #how to convert [1,100,102,106] first to [1,[100,102,106]] to [1:[100,102,106]] - defListToDict1 (): -D=[[1,100,102,106],[2,102,456], [3,789]]; -E={}; in forIinchRange (len (d)): -E[d[i][0]]=d[i][1:]; to returne; +
2-D array/matrix into a dictionary in Python (the first column in the matrix contains duplicate elements)??