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

WBOY
Release: 2016-06-06 11:14:40
Original
2097 people have browsed it

有些时候我们不得已要利用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'
Copy after login

python2.7

>>> d1={'a':1,'b':2}
>>> dict((value,key) for key,value in d1.iteritems())
{1: 'a', 2: 'b'}
Copy after login

如果有重复的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']})
Copy after login

谢特,太牛逼。。。。。

感谢行语者大神的帮助

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template