Home  >  Article  >  Backend Development  >  Python实现字典的key和values的交换

Python实现字典的key和values的交换

WBOY
WBOYOriginal
2016-06-06 11:14:402093browse

有些时候我们不得已要利用values来反向查询key,有没有简单的方法呢?

下面我给大家列举一些方法,方便大家使用

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

如果有重复的key

>>> d1={'a':1,'b':2,'c':1}
>>> d=defaultdict(list)
>>> for k,v in d1.iteritems():
...   d[v].append(k)
... 
>>> d
defaultdict(<type 'list'>, {1: ['a', 'c'], 2: ['b']})

谢特,太牛逼。。。。。

感谢行语者大神的帮助

以上就是本文的全部内容了,希望对大家学习python能够有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn