2-D array/matrix into a dictionary in Python (the first column in the matrix contains duplicate elements)??

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.