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.