简体   繁体   中英

Convert a list of tuples to a dictionary

I have a list of tuples with three elements:

A = [[(72, 1, 2), (96, 1, 4)], 
     [(72, 2, 1), (80, 2, 4)], 
     [], 
     [(96, 4, 1), (80, 4, 2), (70, 4, 5)],
     [(70, 5, 4)],
     ]

I need to convert it to a dictionary in this format (note that the second element in the tuple will be the key):

A_dict = { 1: {2:72, 4:96},
           2: {1:72, 4:80},
           3: {},
           4: {1:96, 2:80, 5:70},
           5: {4:70},
         }

Is there a way to convert A to A_dict?

I tried this:

A_dict = {b:{a:c} for a,b,c in A}

but I got an error:

ValueError: not enough values to unpack (expected 3, got 2)

You can just do:

A_dict = {k+1: {t[2]: t[0] for t in l} for k, l in enumerate(A)}

>>> A_dict
{
 1: {2: 72, 4: 96}, 
 2: {1: 72, 4: 80}, 
 3: {}, 
 4: {1: 96, 2: 80, 5: 70}, 
 5: {4: 70}
}

By iterating on the indices of the list, according to its length. And for each value building its own dictionary:

A_dict = {i + 1 : {v[2] : v[0] for v in A[i]} for i in range(len(A))}

will output:

{1: {2: 72, 4: 96},
 2: {1: 72, 4: 80},
 3: {},
 4: {1: 96, 2: 80, 5: 70},
 5: {4: 70}}

Actually your desired code is:

A_dict = {A[i][0][1] : {v[2] : v[0] for v in A[i]} for i in range(len(A)) if len(A[i]) > 0}

But that will 'skip' the third line, as there is no list, thus not able to determinate the actual key, according to your specification.

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