Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Easy way to switch keys and values in Python dictionary
-
Hi!
I use dictionaries for translating texts between languages. They typically look like this:
trans_en_sv = { 'parish': 'socken', 'county': 'län', 'municipality': 'kommun', 'rune stone': 'runsten', 'rock carving': 'hällristning', 'rune inscribed boulder': 'runhäll', 'runic inscription': 'runinskrift' }
This one is from English to Swedish. If I want to use the same dictionary for translating the other way, is there a smarter way than looping through it and create a new dictionary? I have a feeling there should be some way to just flip around the keys and values on the fly. 🤔
Best regards, Niklas
-
flipped = {value: key for key, value in trans_en_sv.items()}
# dict comprehension -
Thanks! That looked even easier than I had anticipated. 😀 I love Python.
-
@Niklas, ”why can’t I reverse lookup a dict?” Is probably something every Python coder has asked at one point, but the language has no such concept.
If you have a largish dict with lot of additions and reverse lookups, you might not want to reverse the whole dict every time, in which case something like this might be useful.