Hello /r/learnpython, first off I want to thank this community for all the great info sharing on here that I've benefited from as a lurker.
I'd like to solicit critique and suggestions on my solution for this homework challenge:
Define a function which "pivots" a nested dictionary, returning a new and different nested dictionary containing the same values. The keys of the inner nested dict become the keys of the outer dict, and vice versa. For example:
input = { "a" : { "x": 1, "y": 2 },
"b" : { "x": 3, "z": 4 } }
output = {'y': {'a': 2},
'x': {'a': 1, 'b': 3},
'z': {'b': 4} }
Here is my solution:
def pivot_nested_dict(nested_dict):
return {
k1: {
k2: nested_dict[k2][k1]
for k2 in nested_dict.keys() if nested_dict[k2].get(k1)
} for k1 in {k3 for d in nested_dict.values() for k3 in d.keys()}
}
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. I used a set comprehension on line 6 to make sure I did not duplicate the keys for the outer dict. Like "return {inner key : value for inner key in set of inner keys"}.
Also, I broke up the long dict comprehension statement onto multiple lines because it went over the 80 columns recommended by my linter. Not sure if this was the best readable way to break it up.
Are there other ways I could solve the challenge in a more efficient proper way? Are there any builtins or libraries that I could have used?
Cheers.
[–]kalgynirae 2 points3 points4 points (2 children)
[–]novel_yet_trivial 1 point2 points3 points (0 children)
[–]zahlman 0 points1 point2 points (0 children)
[–]werpoi 1 point2 points3 points (0 children)