There's really not much to say about this code, it is straightforward.
Style
These are only nitpicks.
- Generic dictionary keys are typically named
k
instead of i
or j
, but in a specific application a more descriptive name would be even better.
- Collections should be named by their purpose in the application, not their type.
- By convention, assignments and other binary operators should be surrounded by spaces:
a = b
, not a=b
. See PEP 8 for reference, if you're not already aware of it. Following this style guide makes your code easier to read for others.
Code improvements
When iterating over the keys and values of a dictionary at the same time, you can use
for k, v in dic.items():
# ... use k, v ...
instead of
for k in dic:
v = dic[k]
# ...
The nested loop can be transformed to a dictionary comprehension like this:
dic2 = {v: k for k, values in dic.items() for v in values}
You can remember that the order of for
clauses in the comprehension is the same as the order of corresponding nested for
loops.
Potential pitfalls
You should be aware that this transformation from a dictionary of lists to a reverse dictionary only works if all items in the original lists are unique. Counterexample:
>>> dic = {0: [1, 2], 1: [2, 3]}
>>> {v: k for k, values in dic.items() for v in values}
{1: 0, 2: 1, 3: 1} # missing 2: 0
To correct this, the output dictionary should have the same format as the input, namely mapping each of the items in the input lists to a list of corresponding keys.
If the input represents a directed graph (mapping nodes to lists of neighbours), this corresponds to computing the transposed or reversed graph. It can be done by using a collections.defaultdict
. I don't see an easy way to write it as a comprehension in this case.
from collections import defaultdict
graph = {0: [1, 2], 1: [2, 3]}
transposed_graph = defaultdict(list)
for node, neighbours in graph.items():
for neighbour in neighbours:
transposed_graph[neighbour].append(node)
# {1: [0], 2: [0, 1], 3: [1]}