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 实现视频流下载保存MP4的方法

如下所示: # -*- coding:utf-8 -*- import sys import os from glob import glob import requests...

浅谈python 线程池threadpool之实现

首先介绍一下自己使用到的名词: 工作线程(worker):创建线程池时,按照指定的线程数量,创建工作线程,等待从任务队列中get任务; 任务(requests):即工作线程处理的任务,任...

解决Python命令行下退格,删除,方向键乱码(亲测有效)

一、出现原因:readline模块没有安装 二、解决方式: # 安装readline模块 yum -y install readline-devel # 进入Python安装目录 c...

Django文件存储 默认存储系统解析

Django默认使用的文件存储系统'django.core.files.storage.FileSystemStorage'是一个本地存储系统,由settings中的DEFAULT_FI...

python3连接mysql获取ansible动态inventory脚本

Ansible Inventory  介绍 Ansible Inventory 是包含静态 Inventory 和动态 Inventory 两部分的,静态 Inventory...