Python实现字典的key和values的交换
作者:jastme 时间:2021-08-18 03:45:49
有些时候我们不得已要利用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,字典
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python编写WAF与Sqlmap结合实现指纹探测
2022-05-23 08:10:17
![](https://img.aspxhome.com/file/2023/6/103796_0s.png)
浅析php中array_map和array_walk的使用对比
2023-09-10 22:22:28
Linux下利用python实现语音识别详细教程
2022-07-13 15:11:55
![](https://img.aspxhome.com/file/2023/7/65377_0s.png)
Python生成九宫格图片的示例代码
2023-03-16 20:29:38
![](https://img.aspxhome.com/file/2023/7/97637_0s.jpg)
用css+js给网页背景插入flash播放器
2007-10-21 09:27:00
Python实现批量导入1000条xlsx数据
2021-01-11 05:55:47
Python数据分析基础之文件的读取
2022-10-16 21:25:21
python 列表套json字典根据相同的key筛选数据
2022-06-01 08:52:02
Python采集大学教务系统成绩单实战示例
2021-05-13 23:14:43
![](https://img.aspxhome.com/file/2023/5/72715_0s.jpg)
python中的subprocess.Popen()使用详解
2023-08-01 18:55:23
Python表达式的优先级详解
2021-09-21 14:24:59
PHP session反序列化漏洞深入探究
2023-05-30 04:53:04
![](https://img.aspxhome.com/file/2023/7/55367_0s.png)
发散后的期望
2008-07-31 18:32:00
python virtualenv虚拟环境配置与使用教程详解
2023-01-21 23:06:56
![](https://img.aspxhome.com/file/2023/6/87826_0s.png)
Python面向对象基础入门之设置对象属性
2021-10-21 19:25:10
Python selenium模拟网页点击爬虫交管12123违章数据
2023-09-26 18:30:37
![](https://img.aspxhome.com/file/2023/4/67374_0s.jpg)
用ASP实现txt,doc,jpg等文件下载的函数
2007-08-17 13:17:00
javascript中css的float特殊写法
2007-12-24 20:24:00
python实现根据月份和日期得到星座的方法
2023-02-02 01:05:51
合并SQL脚本文件的方法分享
2011-09-30 11:13:03