python

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

养鱼的猫咪
538
2021-03-18 17:07:29
栏目: 编程语言
Python开发者服务器,限时0元免费领! 查看>>

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'}

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

相关推荐:python中字典的items方法怎么使用

0
看了该问题的人还看了