Python implements the exchange of keys and values of a dictionary

Source: Internet
Author: User
There are times when we have to use values to reverse query key, is there a simple way?

I will give you some examples of ways to facilitate the use of people

Python3

>>> d1={' A ': 1, ' B ':2}>>> {Value:key for key,value in D1.iteritems ()}{1: ' A ', 2: ' B '}>>> {value : Key for Key,value in D1.iteritems ()}[2] ' B '

python2.7

>>> d1={' A ': 1, ' B ':2}>>> dict ((value,key) for Key,value in D1.iteritems ()) {1: ' A ', 2: ' B '}

If there is a duplicate key

>>> d1={' A ': 1, ' B ': 2, ' C ':1}>>> d=defaultdict (list) >>> for k,v in D1.iteritems ():   ... D[v].append (k) ... >>> ddefaultdict (
 
 
  
  , {1: [' A ', ' C '], 2: [' B ']})
 
 

Keith, too good .....

Thanks to the help of the great God of the line-speakers

The above is the whole content of this article, I hope to learn Python can help you.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.