当前位置: 首页 > 图灵资讯 > 行业资讯> python如何用函数创造字典

python如何用函数创造字典

发布时间:2024-07-07 19:31:43

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)

以上是python用函数创建字典的方法,希望对大家有所帮助。更多Python学习指导:基础教程python基础教程

本文教程操作环境:windows7系统Python 3.9.1,DELL G3电脑。

相关文章

如何让vim支持python3

如何让vim支持python3

2025-09-12
python2.7和3.6区别有哪些

python2.7和3.6区别有哪些

2025-09-12
python3有serial库吗

python3有serial库吗

2025-09-12
python中w、r表示什么意思

python中w、r表示什么意思

2025-09-12
python中如何把list变成字符串

python中如何把list变成字符串

2025-09-12
python命名空间是什么

python命名空间是什么

2025-09-12