python-多种字典创建方式
2017-04-24 11:26
387 查看
1.创建空字典
>>> dic = {} >>> type(dic) <type 'dict'>1
2
3
1
2
3
2.直接赋值创建
>>> dic = {'spam':1, 'egg':2, 'bar':3} >>> dic {'bar': 3, 'egg': 2, 'spam': 1}1
2
3
1
2
3
3.通过关键字dict和关键字参数创建
>>> dic = dict(spam = 1, egg = 2, bar =3) >>> dic {'bar': 3, 'egg': 2, 'spam': 1}1
2
3
1
2
3
4.通过二元组列表创建
>>> list = [('spam', 1), ('egg', 2), ('bar', 3)] >>> dic = dict(list) >>> dic {'bar': 3, 'egg': 2, 'spam': 1}1
2
3
4
1
2
3
4
5.dict和zip结合创建
>>> dic = dict(zip('abc', [1, 2, 3])) >>> dic {'a': 1, 'c': 3, 'b': 2}1
2
3
1
2
3
6.通过字典推导式创建
>>> dic = {i:2*i for i in range(3)} >>> dic {0: 0, 1: 2, 2: 4}1
2
3
1
2
3
7.通过dict.fromkeys()创建
通常用来初始化字典, 设置value的默认值>>> dic = dict.fromkeys(range(3), 'x') >>> dic {0: 'x', 1: 'x', 2: 'x'}1
2
3
1
2
3
8.其他
>>> list = ['x', 1, 'y', 2, 'z', 3] >>> dic = dict(zip(list[::2], list[1::2])) >>> dic {'y': 2, 'x': 1, 'z': 3}
相关文章推荐
- Python - 创建字典的多种方式
- python创建字典多种方式
- python创建字典多种方式
- Python-Dictionary-创建字典的方式
- python创建字典dict多种方法
- python 从字典里取出内容,创建集合 dict -> set
- python中threading方式创建的线程的终止
- PL/SQL基础编程之(十一)[表空间概述、说明、创建][本地管理和字典管理、切换管理方式]
- Android 中 AlertDialog 的多种创建方式(一)
- python创建桌面快捷方式(pythonwin)及从快捷方式获取文件路径
- python创建和使用字典实例详解
- 各种常用Python字典应用方式详解
- 以支持多种浏览器的方式创建 XMLHttpRequest 对象
- ios 线程多种创建方式
- python字典合并哪种方式效率最高?
- 网页创建快捷方式到桌面多种方法
- [Python] 在 Bottle Web Framework 中以类的方式创建应用
- python_在无须过多援引的情况下创建字典
- 以支持多种浏览器的方式创建 XMLHttpRequest 对象
- python 创建桌面快捷方式