switching keys and values in a dictionary in python












35















Say I have a dictionary like so:



my_dict = {2:3, 5:6, 8:9}


Is there a way that I can switch the keys and values to get:



{3:2, 6:5, 9:8}









share|improve this question




















  • 1





    Are the values unique? Are the values hashable?

    – wim
    Nov 29 '11 at 3:45
















35















Say I have a dictionary like so:



my_dict = {2:3, 5:6, 8:9}


Is there a way that I can switch the keys and values to get:



{3:2, 6:5, 9:8}









share|improve this question




















  • 1





    Are the values unique? Are the values hashable?

    – wim
    Nov 29 '11 at 3:45














35












35








35


14






Say I have a dictionary like so:



my_dict = {2:3, 5:6, 8:9}


Is there a way that I can switch the keys and values to get:



{3:2, 6:5, 9:8}









share|improve this question
















Say I have a dictionary like so:



my_dict = {2:3, 5:6, 8:9}


Is there a way that I can switch the keys and values to get:



{3:2, 6:5, 9:8}






python dictionary key






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 24 '18 at 11:06









ViAik

5019




5019










asked Nov 29 '11 at 3:36









me45me45

3193714




3193714








  • 1





    Are the values unique? Are the values hashable?

    – wim
    Nov 29 '11 at 3:45














  • 1





    Are the values unique? Are the values hashable?

    – wim
    Nov 29 '11 at 3:45








1




1





Are the values unique? Are the values hashable?

– wim
Nov 29 '11 at 3:45





Are the values unique? Are the values hashable?

– wim
Nov 29 '11 at 3:45












8 Answers
8






active

oldest

votes


















61














my_dict2 = dict((y,x) for x,y in my_dict.iteritems())


If you are using python 2.7 or 3.x you can use a dictionary comprehension instead:



my_dict2 = {y:x for x,y in my_dict.iteritems()}


Edit



As noted in the comments by JBernardo, for python 3.x you need to use items instead of iteritems






share|improve this answer





















  • 3





    .iteritems() is not valid on Python 3.x...

    – JBernardo
    Nov 29 '11 at 3:47











  • @JBernardo: Fixed thanks I forgot about that

    – GWW
    Nov 29 '11 at 3:48






  • 1





    another correction - doing the dictionary comprehension you suggest {(y, x) for x, y in dic_cols_w.items()} returns a set, not a dictionary. You would still need to wrap this in a dict(...) to get a dictionary

    – tsando
    Apr 5 '17 at 13:06






  • 3





    @tsando: I think you have read my answer incorrectly. I have {y:x ...

    – GWW
    Apr 5 '17 at 22:34











  • How would you do this if the values were a list of items and each item in the list should be a key?

    – Woody Pride
    Feb 6 at 14:49



















6














Use this code (trivially modified) from the accepted answer at Python reverse / invert a mapping:



dict((v,k) for k, v in my_dict.iteritems())


Note that this assumes that the values in the original dictionary are unique. Otherwise you'd end up with duplicate keys in the resulting dictionary, and that is not allowed.



And, as @wim points out, it also assumes the values are hashable. See the Python glossary if you're not sure what is and isn't hashable.






share|improve this answer

































    5














    Try this:



    my_dict = {2:3, 5:6, 8:9}

    new_dict = {}
    for k, v in my_dict.items():
    new_dict[v] = k





    share|improve this answer































      4














      maybe:



      flipped_dict = dict(zip(my_dict.values(), my_dict.keys()))






      share|improve this answer



















      • 2





        this is probably not safe as it relies on key and value ordering, although it happened to work for me. I like JBernardo/GWW's answer(s).

        – aaron
        Nov 29 '11 at 3:43













      • It's probably better to use iterkeys and itervalues

        – GWW
        Nov 29 '11 at 3:44











      • That's safe if the dict isn't changed during the operation. I liked because you did it without a comprehension.

        – JBernardo
        Nov 29 '11 at 3:51



















      2














      Sometimes, the condition that the values are all unique will not hold, in which case, the answers above will destroy any duplicate values.



      The following rolls the values that might be duplicates up into a list:



      from itertools import count
      dict([(a,[list(d.keys())[i] for i,j in zip(count(), d.values())if j==a in set(d.values())])


      I'm sure there's a better (non-list-comp) method, but I had a problem with the earlier answers, so thought I'd provide my solution in case others have a similar use-case.



      P.S. Don't expect the dict to remain neatly arranged after any changes to the original! This method is a one-time use only on a static dict - you have been warned!






      share|improve this answer































        1














        my_dict = { my_dict[k]:k for k in my_dict}





        share|improve this answer

































          1














          First of all it is not guaranteed that this is possible, since the values of a dictionary can be unhashable.



          In case these are not, we can use a functional approach with:



          reversed_dict = dict(map(reversed, original_dict.items()))





          share|improve this answer































            0














            If the values are not unique this will collide the key space in conversion.
            Best is to keep the keys in list when switching places



            below handles this -



            RvsD = dict()
            for k,v in MyDict.iteritems():
            RsvD.setdefault(v, ).append(k)





            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8305518%2fswitching-keys-and-values-in-a-dictionary-in-python%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              8 Answers
              8






              active

              oldest

              votes








              8 Answers
              8






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              61














              my_dict2 = dict((y,x) for x,y in my_dict.iteritems())


              If you are using python 2.7 or 3.x you can use a dictionary comprehension instead:



              my_dict2 = {y:x for x,y in my_dict.iteritems()}


              Edit



              As noted in the comments by JBernardo, for python 3.x you need to use items instead of iteritems






              share|improve this answer





















              • 3





                .iteritems() is not valid on Python 3.x...

                – JBernardo
                Nov 29 '11 at 3:47











              • @JBernardo: Fixed thanks I forgot about that

                – GWW
                Nov 29 '11 at 3:48






              • 1





                another correction - doing the dictionary comprehension you suggest {(y, x) for x, y in dic_cols_w.items()} returns a set, not a dictionary. You would still need to wrap this in a dict(...) to get a dictionary

                – tsando
                Apr 5 '17 at 13:06






              • 3





                @tsando: I think you have read my answer incorrectly. I have {y:x ...

                – GWW
                Apr 5 '17 at 22:34











              • How would you do this if the values were a list of items and each item in the list should be a key?

                – Woody Pride
                Feb 6 at 14:49
















              61














              my_dict2 = dict((y,x) for x,y in my_dict.iteritems())


              If you are using python 2.7 or 3.x you can use a dictionary comprehension instead:



              my_dict2 = {y:x for x,y in my_dict.iteritems()}


              Edit



              As noted in the comments by JBernardo, for python 3.x you need to use items instead of iteritems






              share|improve this answer





















              • 3





                .iteritems() is not valid on Python 3.x...

                – JBernardo
                Nov 29 '11 at 3:47











              • @JBernardo: Fixed thanks I forgot about that

                – GWW
                Nov 29 '11 at 3:48






              • 1





                another correction - doing the dictionary comprehension you suggest {(y, x) for x, y in dic_cols_w.items()} returns a set, not a dictionary. You would still need to wrap this in a dict(...) to get a dictionary

                – tsando
                Apr 5 '17 at 13:06






              • 3





                @tsando: I think you have read my answer incorrectly. I have {y:x ...

                – GWW
                Apr 5 '17 at 22:34











              • How would you do this if the values were a list of items and each item in the list should be a key?

                – Woody Pride
                Feb 6 at 14:49














              61












              61








              61







              my_dict2 = dict((y,x) for x,y in my_dict.iteritems())


              If you are using python 2.7 or 3.x you can use a dictionary comprehension instead:



              my_dict2 = {y:x for x,y in my_dict.iteritems()}


              Edit



              As noted in the comments by JBernardo, for python 3.x you need to use items instead of iteritems






              share|improve this answer















              my_dict2 = dict((y,x) for x,y in my_dict.iteritems())


              If you are using python 2.7 or 3.x you can use a dictionary comprehension instead:



              my_dict2 = {y:x for x,y in my_dict.iteritems()}


              Edit



              As noted in the comments by JBernardo, for python 3.x you need to use items instead of iteritems







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 29 '11 at 3:48

























              answered Nov 29 '11 at 3:39









              GWWGWW

              33k68796




              33k68796








              • 3





                .iteritems() is not valid on Python 3.x...

                – JBernardo
                Nov 29 '11 at 3:47











              • @JBernardo: Fixed thanks I forgot about that

                – GWW
                Nov 29 '11 at 3:48






              • 1





                another correction - doing the dictionary comprehension you suggest {(y, x) for x, y in dic_cols_w.items()} returns a set, not a dictionary. You would still need to wrap this in a dict(...) to get a dictionary

                – tsando
                Apr 5 '17 at 13:06






              • 3





                @tsando: I think you have read my answer incorrectly. I have {y:x ...

                – GWW
                Apr 5 '17 at 22:34











              • How would you do this if the values were a list of items and each item in the list should be a key?

                – Woody Pride
                Feb 6 at 14:49














              • 3





                .iteritems() is not valid on Python 3.x...

                – JBernardo
                Nov 29 '11 at 3:47











              • @JBernardo: Fixed thanks I forgot about that

                – GWW
                Nov 29 '11 at 3:48






              • 1





                another correction - doing the dictionary comprehension you suggest {(y, x) for x, y in dic_cols_w.items()} returns a set, not a dictionary. You would still need to wrap this in a dict(...) to get a dictionary

                – tsando
                Apr 5 '17 at 13:06






              • 3





                @tsando: I think you have read my answer incorrectly. I have {y:x ...

                – GWW
                Apr 5 '17 at 22:34











              • How would you do this if the values were a list of items and each item in the list should be a key?

                – Woody Pride
                Feb 6 at 14:49








              3




              3





              .iteritems() is not valid on Python 3.x...

              – JBernardo
              Nov 29 '11 at 3:47





              .iteritems() is not valid on Python 3.x...

              – JBernardo
              Nov 29 '11 at 3:47













              @JBernardo: Fixed thanks I forgot about that

              – GWW
              Nov 29 '11 at 3:48





              @JBernardo: Fixed thanks I forgot about that

              – GWW
              Nov 29 '11 at 3:48




              1




              1





              another correction - doing the dictionary comprehension you suggest {(y, x) for x, y in dic_cols_w.items()} returns a set, not a dictionary. You would still need to wrap this in a dict(...) to get a dictionary

              – tsando
              Apr 5 '17 at 13:06





              another correction - doing the dictionary comprehension you suggest {(y, x) for x, y in dic_cols_w.items()} returns a set, not a dictionary. You would still need to wrap this in a dict(...) to get a dictionary

              – tsando
              Apr 5 '17 at 13:06




              3




              3





              @tsando: I think you have read my answer incorrectly. I have {y:x ...

              – GWW
              Apr 5 '17 at 22:34





              @tsando: I think you have read my answer incorrectly. I have {y:x ...

              – GWW
              Apr 5 '17 at 22:34













              How would you do this if the values were a list of items and each item in the list should be a key?

              – Woody Pride
              Feb 6 at 14:49





              How would you do this if the values were a list of items and each item in the list should be a key?

              – Woody Pride
              Feb 6 at 14:49













              6














              Use this code (trivially modified) from the accepted answer at Python reverse / invert a mapping:



              dict((v,k) for k, v in my_dict.iteritems())


              Note that this assumes that the values in the original dictionary are unique. Otherwise you'd end up with duplicate keys in the resulting dictionary, and that is not allowed.



              And, as @wim points out, it also assumes the values are hashable. See the Python glossary if you're not sure what is and isn't hashable.






              share|improve this answer






























                6














                Use this code (trivially modified) from the accepted answer at Python reverse / invert a mapping:



                dict((v,k) for k, v in my_dict.iteritems())


                Note that this assumes that the values in the original dictionary are unique. Otherwise you'd end up with duplicate keys in the resulting dictionary, and that is not allowed.



                And, as @wim points out, it also assumes the values are hashable. See the Python glossary if you're not sure what is and isn't hashable.






                share|improve this answer




























                  6












                  6








                  6







                  Use this code (trivially modified) from the accepted answer at Python reverse / invert a mapping:



                  dict((v,k) for k, v in my_dict.iteritems())


                  Note that this assumes that the values in the original dictionary are unique. Otherwise you'd end up with duplicate keys in the resulting dictionary, and that is not allowed.



                  And, as @wim points out, it also assumes the values are hashable. See the Python glossary if you're not sure what is and isn't hashable.






                  share|improve this answer















                  Use this code (trivially modified) from the accepted answer at Python reverse / invert a mapping:



                  dict((v,k) for k, v in my_dict.iteritems())


                  Note that this assumes that the values in the original dictionary are unique. Otherwise you'd end up with duplicate keys in the resulting dictionary, and that is not allowed.



                  And, as @wim points out, it also assumes the values are hashable. See the Python glossary if you're not sure what is and isn't hashable.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited May 23 '17 at 12:10









                  Community

                  11




                  11










                  answered Nov 29 '11 at 3:41









                  TrottTrott

                  37.9k19104152




                  37.9k19104152























                      5














                      Try this:



                      my_dict = {2:3, 5:6, 8:9}

                      new_dict = {}
                      for k, v in my_dict.items():
                      new_dict[v] = k





                      share|improve this answer




























                        5














                        Try this:



                        my_dict = {2:3, 5:6, 8:9}

                        new_dict = {}
                        for k, v in my_dict.items():
                        new_dict[v] = k





                        share|improve this answer


























                          5












                          5








                          5







                          Try this:



                          my_dict = {2:3, 5:6, 8:9}

                          new_dict = {}
                          for k, v in my_dict.items():
                          new_dict[v] = k





                          share|improve this answer













                          Try this:



                          my_dict = {2:3, 5:6, 8:9}

                          new_dict = {}
                          for k, v in my_dict.items():
                          new_dict[v] = k






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 29 '11 at 3:40









                          Óscar LópezÓscar López

                          178k25227323




                          178k25227323























                              4














                              maybe:



                              flipped_dict = dict(zip(my_dict.values(), my_dict.keys()))






                              share|improve this answer



















                              • 2





                                this is probably not safe as it relies on key and value ordering, although it happened to work for me. I like JBernardo/GWW's answer(s).

                                – aaron
                                Nov 29 '11 at 3:43













                              • It's probably better to use iterkeys and itervalues

                                – GWW
                                Nov 29 '11 at 3:44











                              • That's safe if the dict isn't changed during the operation. I liked because you did it without a comprehension.

                                – JBernardo
                                Nov 29 '11 at 3:51
















                              4














                              maybe:



                              flipped_dict = dict(zip(my_dict.values(), my_dict.keys()))






                              share|improve this answer



















                              • 2





                                this is probably not safe as it relies on key and value ordering, although it happened to work for me. I like JBernardo/GWW's answer(s).

                                – aaron
                                Nov 29 '11 at 3:43













                              • It's probably better to use iterkeys and itervalues

                                – GWW
                                Nov 29 '11 at 3:44











                              • That's safe if the dict isn't changed during the operation. I liked because you did it without a comprehension.

                                – JBernardo
                                Nov 29 '11 at 3:51














                              4












                              4








                              4







                              maybe:



                              flipped_dict = dict(zip(my_dict.values(), my_dict.keys()))






                              share|improve this answer













                              maybe:



                              flipped_dict = dict(zip(my_dict.values(), my_dict.keys()))







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 29 '11 at 3:41









                              aaronaaron

                              835812




                              835812








                              • 2





                                this is probably not safe as it relies on key and value ordering, although it happened to work for me. I like JBernardo/GWW's answer(s).

                                – aaron
                                Nov 29 '11 at 3:43













                              • It's probably better to use iterkeys and itervalues

                                – GWW
                                Nov 29 '11 at 3:44











                              • That's safe if the dict isn't changed during the operation. I liked because you did it without a comprehension.

                                – JBernardo
                                Nov 29 '11 at 3:51














                              • 2





                                this is probably not safe as it relies on key and value ordering, although it happened to work for me. I like JBernardo/GWW's answer(s).

                                – aaron
                                Nov 29 '11 at 3:43













                              • It's probably better to use iterkeys and itervalues

                                – GWW
                                Nov 29 '11 at 3:44











                              • That's safe if the dict isn't changed during the operation. I liked because you did it without a comprehension.

                                – JBernardo
                                Nov 29 '11 at 3:51








                              2




                              2





                              this is probably not safe as it relies on key and value ordering, although it happened to work for me. I like JBernardo/GWW's answer(s).

                              – aaron
                              Nov 29 '11 at 3:43







                              this is probably not safe as it relies on key and value ordering, although it happened to work for me. I like JBernardo/GWW's answer(s).

                              – aaron
                              Nov 29 '11 at 3:43















                              It's probably better to use iterkeys and itervalues

                              – GWW
                              Nov 29 '11 at 3:44





                              It's probably better to use iterkeys and itervalues

                              – GWW
                              Nov 29 '11 at 3:44













                              That's safe if the dict isn't changed during the operation. I liked because you did it without a comprehension.

                              – JBernardo
                              Nov 29 '11 at 3:51





                              That's safe if the dict isn't changed during the operation. I liked because you did it without a comprehension.

                              – JBernardo
                              Nov 29 '11 at 3:51











                              2














                              Sometimes, the condition that the values are all unique will not hold, in which case, the answers above will destroy any duplicate values.



                              The following rolls the values that might be duplicates up into a list:



                              from itertools import count
                              dict([(a,[list(d.keys())[i] for i,j in zip(count(), d.values())if j==a in set(d.values())])


                              I'm sure there's a better (non-list-comp) method, but I had a problem with the earlier answers, so thought I'd provide my solution in case others have a similar use-case.



                              P.S. Don't expect the dict to remain neatly arranged after any changes to the original! This method is a one-time use only on a static dict - you have been warned!






                              share|improve this answer




























                                2














                                Sometimes, the condition that the values are all unique will not hold, in which case, the answers above will destroy any duplicate values.



                                The following rolls the values that might be duplicates up into a list:



                                from itertools import count
                                dict([(a,[list(d.keys())[i] for i,j in zip(count(), d.values())if j==a in set(d.values())])


                                I'm sure there's a better (non-list-comp) method, but I had a problem with the earlier answers, so thought I'd provide my solution in case others have a similar use-case.



                                P.S. Don't expect the dict to remain neatly arranged after any changes to the original! This method is a one-time use only on a static dict - you have been warned!






                                share|improve this answer


























                                  2












                                  2








                                  2







                                  Sometimes, the condition that the values are all unique will not hold, in which case, the answers above will destroy any duplicate values.



                                  The following rolls the values that might be duplicates up into a list:



                                  from itertools import count
                                  dict([(a,[list(d.keys())[i] for i,j in zip(count(), d.values())if j==a in set(d.values())])


                                  I'm sure there's a better (non-list-comp) method, but I had a problem with the earlier answers, so thought I'd provide my solution in case others have a similar use-case.



                                  P.S. Don't expect the dict to remain neatly arranged after any changes to the original! This method is a one-time use only on a static dict - you have been warned!






                                  share|improve this answer













                                  Sometimes, the condition that the values are all unique will not hold, in which case, the answers above will destroy any duplicate values.



                                  The following rolls the values that might be duplicates up into a list:



                                  from itertools import count
                                  dict([(a,[list(d.keys())[i] for i,j in zip(count(), d.values())if j==a in set(d.values())])


                                  I'm sure there's a better (non-list-comp) method, but I had a problem with the earlier answers, so thought I'd provide my solution in case others have a similar use-case.



                                  P.S. Don't expect the dict to remain neatly arranged after any changes to the original! This method is a one-time use only on a static dict - you have been warned!







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Jul 29 '16 at 20:48









                                  Thomas KimberThomas Kimber

                                  3,36921323




                                  3,36921323























                                      1














                                      my_dict = { my_dict[k]:k for k in my_dict}





                                      share|improve this answer






























                                        1














                                        my_dict = { my_dict[k]:k for k in my_dict}





                                        share|improve this answer




























                                          1












                                          1








                                          1







                                          my_dict = { my_dict[k]:k for k in my_dict}





                                          share|improve this answer















                                          my_dict = { my_dict[k]:k for k in my_dict}






                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Jul 19 '16 at 11:39









                                          Ingo Karkat

                                          132k14148199




                                          132k14148199










                                          answered Jul 19 '16 at 11:21









                                          VladEgVladEg

                                          111




                                          111























                                              1














                                              First of all it is not guaranteed that this is possible, since the values of a dictionary can be unhashable.



                                              In case these are not, we can use a functional approach with:



                                              reversed_dict = dict(map(reversed, original_dict.items()))





                                              share|improve this answer




























                                                1














                                                First of all it is not guaranteed that this is possible, since the values of a dictionary can be unhashable.



                                                In case these are not, we can use a functional approach with:



                                                reversed_dict = dict(map(reversed, original_dict.items()))





                                                share|improve this answer


























                                                  1












                                                  1








                                                  1







                                                  First of all it is not guaranteed that this is possible, since the values of a dictionary can be unhashable.



                                                  In case these are not, we can use a functional approach with:



                                                  reversed_dict = dict(map(reversed, original_dict.items()))





                                                  share|improve this answer













                                                  First of all it is not guaranteed that this is possible, since the values of a dictionary can be unhashable.



                                                  In case these are not, we can use a functional approach with:



                                                  reversed_dict = dict(map(reversed, original_dict.items()))






                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Jan 19 '18 at 10:25









                                                  Willem Van OnsemWillem Van Onsem

                                                  148k16142232




                                                  148k16142232























                                                      0














                                                      If the values are not unique this will collide the key space in conversion.
                                                      Best is to keep the keys in list when switching places



                                                      below handles this -



                                                      RvsD = dict()
                                                      for k,v in MyDict.iteritems():
                                                      RsvD.setdefault(v, ).append(k)





                                                      share|improve this answer




























                                                        0














                                                        If the values are not unique this will collide the key space in conversion.
                                                        Best is to keep the keys in list when switching places



                                                        below handles this -



                                                        RvsD = dict()
                                                        for k,v in MyDict.iteritems():
                                                        RsvD.setdefault(v, ).append(k)





                                                        share|improve this answer


























                                                          0












                                                          0








                                                          0







                                                          If the values are not unique this will collide the key space in conversion.
                                                          Best is to keep the keys in list when switching places



                                                          below handles this -



                                                          RvsD = dict()
                                                          for k,v in MyDict.iteritems():
                                                          RsvD.setdefault(v, ).append(k)





                                                          share|improve this answer













                                                          If the values are not unique this will collide the key space in conversion.
                                                          Best is to keep the keys in list when switching places



                                                          below handles this -



                                                          RvsD = dict()
                                                          for k,v in MyDict.iteritems():
                                                          RsvD.setdefault(v, ).append(k)






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Dec 23 '18 at 3:56









                                                          mungayreemungayree

                                                          1118




                                                          1118






























                                                              draft saved

                                                              draft discarded




















































                                                              Thanks for contributing an answer to Stack Overflow!


                                                              • Please be sure to answer the question. Provide details and share your research!

                                                              But avoid



                                                              • Asking for help, clarification, or responding to other answers.

                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                              To learn more, see our tips on writing great answers.




                                                              draft saved


                                                              draft discarded














                                                              StackExchange.ready(
                                                              function () {
                                                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8305518%2fswitching-keys-and-values-in-a-dictionary-in-python%23new-answer', 'question_page');
                                                              }
                                                              );

                                                              Post as a guest















                                                              Required, but never shown





















































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown

































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown







                                                              Popular posts from this blog

                                                              404 Error Contact Form 7 ajax form submitting

                                                              How to know if a Active Directory user can login interactively

                                                              TypeError: fit_transform() missing 1 required positional argument: 'X'