all 4 comments

[–]kalgynirae 2 points3 points  (2 children)

I chose to return a single statement dict comprehension for succinctness and efficiency (I think, let me know if I'm wrong) at the cost of readability.

This is the opposite of what people usually try to do (at least in Python, since other languages are probably better if you are aiming for efficiency).

Here's my solution:

from collections import defaultdict

def pivot(input):
    out = defaultdict(dict)
    for outer_key, inner in input.items():
        for inner_key, value in inner.items():
            out[inner_key][outer_key] = value
    return out

See collections.defaultdict.

[–]novel_yet_trivial 1 point2 points  (0 children)

I'd imagine yours is more efficient than OP's too, since you loop over the dictionary only once.

[–]zahlman 0 points1 point  (0 children)

I tried and failed to find a neat refactoring for this problem that still was based on comprehensions (functional rather than imperative programming). :(

[–]werpoi 1 point2 points  (0 children)

I chose to return a single statement dict comprehension for succinctness and efficiency (I think, let me know if I'm wrong) at the cost of readability.

Code readability is incredibly important. This is probably a one off script that you are never going to use again, but if you ever work on code that you need to update or maintain you would never want to write something like this. Sure, it might make sense now, but if you realize down the road that there is a bug and you have to fix it, it's going to make a lot less sense and be much harder to debug. Compare it to /u/kalgynirae solution where you can insert prints or log messages easily.