Skip to content Skip to sidebar Skip to footer

Nested List To Dict With Count Groups

I have nested list: L = [[15,10], [11], [9,7,8]] and need count groups like [15, 10] is 0 group, [11] is 1 group and [9,7,8] is 2 group - output is dictionary: print (d) {7: 2, 8:

Solution 1:

What about using:

d = {v: i for i,l in enumerate(L) for v in l}

which generates:

>>> {v: i for i,l in enumerate(L) for v in l}
{7: 2, 8: 2, 9: 2, 10: 0, 11: 1, 15: 0}

The idea is as follows: first we iterate over L with enumerate(L) and we thus obtain the index i of the sublist vs. Next we iterate over every element v in vs. For every v we associate v with i in the dictionary.

If there are collisions - a value that occurs twice in L - then the last index will be used.


Solution 2:

You can use:

d = {v: i for i in range(len(L)) for v in L[i]}

output:

{7: 2, 8: 2, 9: 2, 10: 0, 11: 1, 15: 0}

iterating over L using range(len(L)) to access each list and assign each value as the key of the dictionary, and the index of the list as the value.


Post a Comment for "Nested List To Dict With Count Groups"