jezrael
jezrael

Reputation: 863801

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: 2, 9: 2, 10: 0, 11: 1, 15: 0}

I try:

d = {k:v for k,v in enumerate(L)}
d = {k: oldk for oldk, oldv in d.items() for k in oldv}
print (d)
{7: 2, 8: 2, 9: 2, 10: 0, 11: 1, 15: 0}

I think my solution is a bit over-complicated. Is there some better, more pythonic solution?

Upvotes: 1

Views: 99

Answers (2)

Mohd
Mohd

Reputation: 5613

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.

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477881

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.

Upvotes: 2

Related Questions