List comprehension inside dictionary comprehension - scope

4.8k views Asked by At

I am trying to create a complete graph in a Python Dictionary in 1 line. But when creating the list comprehension for the values I can not figure out how to specify that the key_value can not appear in the list of values (in graph speak, no self loop).

for n nodes

G = {k:[v for v in range(n)] for k in range(n) }

results in this (example n = 3)

{0: [0, 1, 2], 1: [0, 1, 2], 2: [0, 1, 2]}

but what I want is this

{0: [1, 2], 1: [0, 2], 2: [0, 1]}

But trying something similar to this

G = {k:[v for v in range(n) for v !=k] for k in range(n) }

will throw an error at the k in the list comprehension. So k must be out of scope for the list comprehension, which makes sense.

Can G be defined in this method?

1

There are 1 answers

0
Tanveer Alam On BEST ANSWER

To ignore the key's value from the value list, you just have to put a validation in your list comprehension.

G = { k: [v for v in range(n) if v != k] for k in range(n) }

So for n = 3 you graph G would return :-

{0: [1, 2], 1: [0, 2], 2: [0, 1]}