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