Python implements the exchange of dictionary keys and values

Source: Internet
Author: User
This article introduces the program code that implements Dictionary key and values exchange in python3.0 and 2.7 respectively. it is very simple and practical. if you need it, you can refer to it. Sometimes we have to use values to reverse query the key. Is there a simple way?

Below are some examples for your convenience.

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 duplicate keys exist

>>> 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']})

 

That's awesome .....

Thank you for your help.

The above is all the content of this article. I hope it will help you learn python.

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.