3
\$\begingroup\$

I'm working on the following problem: I've got a dictionary like this one:

dic={0:[0,1,2],1:[3,4,5]}

And I want to reverse it so it looks like this:

dic2={0:0,1:0,2:0,3:1,4:1,5:1}

I managed to make it, but doing this:

dic2={}
for i in dic:
    for j in dic[i]:
        dic2[j]=i

I know about list and dict comprehensions and this code reeks of it, but I'm not good at them when there are nested for and dicts. How would you make it more efficiently?

\$\endgroup\$
6
\$\begingroup\$

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]}
\$\endgroup\$
  • 1
    \$\begingroup\$ Also, it's important to use an entry point in Python - the classic if __name__ == "__main__": because tools like Sphinx which auto-document code will load the code to reflect what properties and methods each object has. Having the entry point separates the execution of the code, from the code itself (does that make sense?). The code in the current form will always execute, as opposed to having something like do_transpose(graph) after the entry point responsible for execution. \$\endgroup\$ – C. Harley Apr 4 at 3:54
  • \$\begingroup\$ Way better answer than what I was expecting and just what I need. I don't come from a programming career, so I'm learning the conventions as I go, so this was really helpful. Thanks a lot to both of you ! \$\endgroup\$ – Juan C Apr 4 at 15:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.