Article was originally posted on therenegadecoder.com where it's actively maintained.
In this series, I’m putting together several articles for sm...
For further actions, you may consider blocking this person and/or reporting abuse
You can also use zip if you don't mind non-unique values being merged:
Good point! I always hesitate with this solution because it’s not immediately clear that the two collections would maintain their order. I know they do, but it still bothers me.
Yeah, the dict comprehension is the clearest way of doing this.
zip
is mildly faster but I agree calling keys and values separately is slightly offputting:Inverting the original dict with non-unique values can be done cleaner (without the explicit two line
for
loop and IMO easier to read) using adefaultdict
:Or to make it more intuitive denote the comprehension using a
dict
since that is what we are applying the operation to:Great addition! I would prefer to maintain the dict type and leave out any extraneous imports, but this gets the job done and is probably less error prone.
Mind if I add it to the list?
Go ahead :)
It's part of the standard library and it's still a dict so you can use any it like a normal dict, e.g.
my_dict_inverted['One for All']
as well as all methods from a normal dict likekeys()
,values()
anditems()
.Hi again! I'm in the process of updating this article, and I just realized that this answer has a minor problem. We're using a dictionary comprehension in a bad way. We're updating some external dictionary while the comprehension will also generate a dictionary (in this case,
{None}
). I believe that's considered bad practice, so I've added a note in the original article.