2022
我们一起努力

服务器vps,python中可以使用哪些方法创建字典

python创建字典的方法:1.通过dict关键字创建;2.通过二元组列表创建;3.通过字典推导式创建;4.通过dict.fromkeys()函数创建;

python中可以使用哪些方法创建字典

在python中创建字典的方法有以下几种

1.通过dict关键字创建

>>> dic = dict(spam = 1, egg = 2, bar =3)

>>> dic

{'bar': 3, 'egg': 2, 'spam': 1}


2.通过二元组列表创建

>>> list = [('spam', 1), ('egg', 2), ('bar', 3)]

>>> dic = dict(list)

>>> dic

{'bar': 3, 'egg': 2, 'spam': 1}


3.通过字典推导式创建

>>> dic = {i:2*i for i in range(3)}

>>> dic

{0: 0, 1: 2, 2: 4}


4.通过dict.fromkeys()函数创建

>>> dic = dict.fromkeys(range(3), 'x')

>>> dic

{0: 'x', 1: 'x', 2: 'x'}


赞(0)
文章名称:《服务器vps,python中可以使用哪些方法创建字典》
文章链接:https://www.fzvps.com/64078.html
本站文章来源于互联网,如有侵权,请联系管理删除,本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。
图片版权归属各自创作者所有,图片水印出于防止被无耻之徒盗取劳动成果的目的。

评论 抢沙发

评论前必须登录!