Python 互换字典的键值对实例

yipeiwu_com6年前Python基础

1.zip

dic = {'a':1, 'b':2, 'c':3}
dic_new = dict(zip(dic.values(), dic.keys()))
print(dic_new)
# {1: 'a', 2: 'b', 3: 'c'}

2.循环

dic = {'a':1, 'b':2, 'c':3}
dic_new = {}
for key, val in dic.items():
  dic_new[val] = key
print(dic_new)
# {1: 'a', 2: 'b', 3: 'c'}

3.列表生成器

dic_new = dict([val, key] for key, val in dic.items())
print(dic_new)
# {1: 'a', 2: 'b', 3: 'c'}

以上这篇Python 互换字典的键值对实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python处理xml文件的方法小结

本文实例讲述了python处理xml文件的方法。分享给大家供大家参考,具体如下: 前一段时间因为工作的需要,学习了一点用Python处理xml文件的方法,现在贴出来,供大家参考。 xml...

python实现的读取网页并分词功能示例

python实现的读取网页并分词功能示例

本文实例讲述了python实现的读取网页并分词功能。分享给大家供大家参考,具体如下: 这里使用分词使用最流行的分词包jieba,参考:https://github.com/fxsjy/j...

python删除列表内容

今天有点囧 a=['XXXX_game.sql', 'XXXX_game_sp.sql', 'XXXX_gamelog_sp.sql', 'XXXX_gamelog.sql'] fo...

在django-xadmin中APScheduler的启动初始化实例

环境: python3.5.x + django1.9.x + xadmin-for-python3 APScheduler做为一个轻量级和使用量很多的后台任务计划(scheduler)...

Python实现串口通信(pyserial)过程解析

pyserial模块封装了对串口的访问,兼容各种平台。 安装 pip insatll pyserial 初始化 简单初始化示例 import serial ser = se...