Python之字典对象的几种创建方法
作者:叫我王员外就行 时间:2023-04-28 13:15:57
第一种方式:使用{}
firstDict = {"name": "wang yuan wai ", "age" : 25}
说明:{}为创建一个空的字典对象
第二种方式:使用fromkeys()方法
second_dict = dict.fromkeys(("name", "age")) #value使用默认的None,也可以指定value值
说明:fromkeys()是dict类的一个staticmethod(静态方法)
第三种方式:使用dict的构造方法,参数为关键字参数
thirdDict = dict(name = "yuan wai", age = 30) #利用dict的构造方法 传入字典参数
第四种方式:使用dict的构造方法,参数为嵌套元组的list
tuple_list =[("name", "wang yuan wai"), ("age", 30)]
说明:传入的list结构是有要求的,list的每个元素都是一个两个元素的tuple
第五种方式:使用dict的构造方法,参数为zip()函数的返回值
fifthDict = dict(zip("abc",[1,2,3]))
第六种方式:使用字典解析式
sixthDict = {char : char* 2 for char in "TEMP"}
创建字典,官方文档
以下示例返回的字典均等于 {"one": 1, "two": 2, "three": 3}:
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
来源:https://blog.csdn.net/cadi2011/article/details/86647835
标签:Python,字典,创建
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Layui表格监听行单双击事件讲解
2024-04-19 10:45:00
![](https://img.aspxhome.com/file/2023/2/135782_0s.jpg)
获取SQL Server数据库元数据的几种方法
2024-01-17 16:00:44
Python爬虫设置Cookie解决网站拦截并爬取蚂蚁短租的问题
2022-06-09 20:07:37
![](https://img.aspxhome.com/file/2023/9/109659_0s.jpg)
基于idea操作hbase数据库并映射到hive表
2024-01-19 23:22:57
![](https://img.aspxhome.com/file/2023/7/110867_0s.png)
使用python调用zxing库生成二维码图片详解
2022-03-19 06:41:09
![](https://img.aspxhome.com/file/2023/7/90787_0s.png)
用pickle存储Python的原生对象方法
2023-10-31 04:43:13
python实操练习案例(六)
2021-01-06 08:09:23
![](https://img.aspxhome.com/file/2023/3/127843_0s.png)
解决idea git切换多个分支后maven不生效的问题
2023-06-28 17:48:13
![](https://img.aspxhome.com/file/2023/7/132257_0s.png)
pyqt5中动画的使用详解
2023-06-29 19:31:51
![](https://img.aspxhome.com/file/2023/2/65102_0s.jpg)
Pytorch Tensor的索引与切片例子
2022-12-08 16:28:10
CentOS 7中源码安装MySQL 5.7.6+详细教程
2024-01-24 13:12:27
python的Jenkins接口调用方式
2022-02-23 11:26:23
![](https://img.aspxhome.com/file/2023/5/89195_0s.jpg)
一道求$b相对于$a的相对路径的php代码
2023-07-12 05:37:46
解决Python requests 报错方法集锦
2023-05-05 20:21:27
vue 遮罩层阻止默认滚动事件操作
2024-04-30 08:42:25
Go语言快速入门图文教程
2023-07-23 10:30:16
![](https://img.aspxhome.com/file/2023/7/95367_0s.jpg)
python新手经常遇到的17个错误分析
2021-08-09 21:46:00
运行SQL Server的计算机间移动数据库
2009-01-20 13:07:00
golang简单获取上传文件大小的实现代码
2024-05-21 10:22:09
利用python爬取斗鱼app中照片方法实例
2022-01-03 17:40:39
![](https://img.aspxhome.com/file/2023/9/75879_0s.png)