List Accounting Inside Dictionary Understanding - Area

I am trying to create a complete graph in a Python Dictionary in 1 line. But when creating an understanding of the list for values, I cannot figure out how to indicate that the key_value value cannot appear in the list of values ​​(they say in the graph that there is no self loop).

for n nodes

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

leads to this (example n = 3)

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

but i want this

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

But having tried something like this

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

throws an error in k in the list comprehension. Thus, k should be inaccessible to the list, which makes sense.

Is it possible to determine G in this method?

+4
source share
1 answer

To ignore key valuefrom the list value, you just need to put the check in your understanding.

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

So, for n = 3you will see a graph G: -

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

All Articles