omz:forum

    • Register
    • Login
    • Search
    • Recent
    • Popular

    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

    Pythonista
    3
    4
    1933
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • Niklas
      Niklas last edited by

      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

      mikael 1 Reply Last reply Reply Quote 0
      • ccc
        ccc last edited by

        flipped = {value: key for key, value in trans_en_sv.items()} # dict comprehension

        1 Reply Last reply Reply Quote 0
        • Niklas
          Niklas last edited by

          Thanks! That looked even easier than I had anticipated. 😀 I love Python.

          1 Reply Last reply Reply Quote 0
          • mikael
            mikael @Niklas last edited by mikael

            @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.

            1 Reply Last reply Reply Quote 0
            • First post
              Last post
            Powered by NodeBB Forums | Contributors