【python学习笔记】字典

本文介绍了Python中的字典类型,包括字典的含义、创建和访问方式、特点及内置方法。字典作为映射类型,以键值对形式存储,提供快速存取。文章还列举了字典的各种操作,如fromkeys()、items()、get()、clear()、copy()、pop()、popitem()、setdefault()和update()等,并给出了相关的编程作业题。
摘要由CSDN通过智能技术生成

1.字典的含义

① 字典是python中唯一的映射类型

② python的字典为键值对,有些地方称为hash,有些地方称之为关系数组

③ 映射类型区别于序列类型,序列类型以数组的方式进行存储,通过索引的方式获取相对应位置的值,一般索引与对应位置存储的数据毫无关系

2.创建和访问字典

① 空字典

>>> empty = {}
>>> type(empty)
<class 'dict'>

② 直接创建字典

>>> dic = {'x':'hello','y':'world'}
>>> type(dic)
<class 'dict'>
>>> 

③ 用dict()函数创建字典

>>> dict1 = dict((('F',70),('G',80),('H',90)))
>>> dict1
{'F': 70, 'G': 80, 'H': 90}
>>> a = dict(one=1,two=2,three=3)
>>> a
{'one': 1, 'two': 2, 'three': 3}
>>> b = {'one':1,'two':2,'three':3}
>>> b
{'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one','two','three'],[1,2,3]))
>>> c
{'one': 1, 'two': 2, 'three': 3}
>>> d = dict([('one',1),('two',2),('three',3)])
>>> d
{'one': 1, 'two': 2, 'three': 3}
>>> e = dict({'one':1,'two':2,'three':3})
>>> e
{'one': 1, 'two': 2, 'three': 3}
>>> a == b == c == d == e 
True
>>> 

④ 直接给字典赋值进行创建,也可以修改值

>>> dict1 = {}
>>> dict1['one'] = 1
>>> dict1['two'] = 2
>>> dict1['three'] = 3
>>> dict1
{'one': 1, 'two': 2, 'three': 3}
>>> 
>>> dict1 = {'one': 1, 'two': 2, 'three': 3}
>>> dict1['one'] = 3
>>> dict1
{'one': 3, 'two': 2, 'three': 3}
>>> dict1['four'] = 4
>>> dict1
{'one': 3, 'two': 2, 'three': 3, 'four': 4}
>>> 

3.字典的特点

① 可存放多个值,key-value存取,取值速度快

>>> empty = {}
>>> type(empty)
<class 'dict'>
>>> dic = {'x':'hello','y':'world'}
>>> type(dic)
<class 'dict'>
>>> 

② key必须是不可变类型(数、元组、字符串),value可以是任何类型

>>> dic = {1:'hello',2:'world'}
>>> dic = {'x':'hello','y':'world'}
>>> dic = {(1,2,3):'hello','y':'world'}
>>> dic = {[1,2,3]:'hello','y':'world'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> dic = {
  {1,2,3}:'hello','y':'world'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> dic = {
  {'x':'hello'}:'hello','y':'world'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

③ 可修改指定key对应的值,可变

>>> dict1 = {'one': 1, 'two': 2, 'three': 3}
>>> dict1['one'] = 3
>>> dict1
{'one': 3, 'two': 2, 'three': 3}

③ 讲究映射,不讲顺序

>>> dict1[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <m
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值