python用函数创造字典的实例讲解
作者:小妮浅浅 时间:2021-04-20 13:55:11
1、使用dict()函数,通过其他映射(比如其他字典)或者键,值对的序列建立字典。
dict1 = dict(a='a', b='b', t='t') # 传入关键字
print(dict1)
dict2 = dict(zip(['one', 'two', 'three'], [1, 2, 3])) # 映射函数方式来构造字典
print(dict2)
dict3 = dict([('one', 1), ('two', 2), ('three', 3)]) # 可迭代对象方式来构造字典
print(dict3)
2、使用fromkeys()函数,只用来创建新字典,不负责保存。
当通过一个字典来调用 fromkeys 方法时,如果需要后续使用一定记得给他复制给其他的变量。
dict3 = dict.fromkeys(['name','age'])
print(dict3)
dict4 = dict.fromkeys(['name','age'],10)
print(dict4)
实例扩展:
代码:字典示例
people = {
'libai':{'phone':'189','addr':'jiangxi'},'lilei':{'phone':'180','adder':'hunan'},
'lihong':{'phone':'152','adder':'hubei'},'liming':{'phone':'153','adder':'tianjing'},
'licheng':{'phone':'154','adder':'beijing'}}
name = input('name:')
if name in people: print("{}'s phone number is {}, address is {}."
.format(name,people[name]['phone'],people[name]['adder']))
#实际运行
#name:liming
#liming's phone number is 153, address is tianjing.
#个人感觉书中的代码写的比较繁琐,初学者看起来可能会比较吃力,重新写了比较简单的版本供参考。
来源:https://www.py.cn/jishu/jichu/31226.html
标签:python,函数,创造字典
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
超越MYSQL,ACCESS复合承载
2008-12-09 13:31:00
解析array splice的移除数组中指定键的值,返回一个新的数组
2023-11-18 09:51:28
Python实现文件压缩和解压的示例代码
2022-04-10 08:20:19
Django操作cookie的实现
2023-06-07 17:05:21
![](https://img.aspxhome.com/file/2023/1/77011_0s.jpg)
在Python的struct模块中进行数据格式转换的方法
2021-09-26 14:24:40
![](https://img.aspxhome.com/file/2023/6/101176_0s.jpg)
PDO取Oracle lob大字段,当数据量太大无法取出的问题的解决办法
2009-04-30 18:41:00
使用python调用zxing库生成二维码图片详解
2022-03-19 06:41:09
![](https://img.aspxhome.com/file/2023/7/90787_0s.png)
三步实现Django Paginator分页的方法
2022-09-22 20:15:31
![](https://img.aspxhome.com/file/2023/6/90806_0s.png)
CSS 表格元素内容的定位 0
2008-08-01 17:31:00
深入理解Pytorch中的torch. matmul()
2023-06-03 05:29:18
![](https://img.aspxhome.com/file/2023/5/107175_0s.jpg)
python引入不同文件夹下的自定义模块方法
2023-04-24 18:37:22
![](https://img.aspxhome.com/file/2023/5/86535_0s.jpg)
SQL脚本语言学习(黑客篇)
2008-02-29 13:09:00
W3C优质网页小贴士(一)
2008-04-06 16:35:00
![](https://img.aspxhome.com/file/UploadPic/up/2008040712541063.gif)
python 安装virtualenv和virtualenvwrapper的方法
2023-04-23 11:27:33
Python+matplotlib实现绘制等高线图示例详解
2022-09-18 05:44:11
![](https://img.aspxhome.com/file/2023/2/112022_0s.jpg)
PyQt5创建一个新窗口的实例
2021-12-31 02:49:44
![](https://img.aspxhome.com/file/2023/6/93516_0s.jpg)
Python通过pytesseract库实现识别图片中的文字
2021-12-02 14:43:03
![](https://img.aspxhome.com/file/2023/0/86130_0s.png)
15个短代码示例理解python丰富的编程思维
2022-07-18 08:16:57
JS+ASP实现无刷新新闻列表之分页
2007-08-22 12:57:00
什么样的图标更具有可用性
2007-10-16 17:47:00
![](https://img.aspxhome.com/file/UploadPic/200710/16/20071016174919899s.jpg)