前言
提示:这里可以添加本文要记录的大概内容:
字典是无序可变序列。类似于其他编程语言中的map
定义字典时,每个元素的键和值用冒号:分隔,元素之间用逗号,分隔,所有的元素放在一对大括号 { } 中。
字典中的键可以为任意不可变数据,比如整数、实数、复数、字符串、元组等等。
{‘a’:1,‘b’:2}
globals()返回包含当前作用域内所有全局变量和值的字典
locals()返回包含当前作用域内所有局部变量和值的字典
提示:以下是本篇文章正文内容,下面案例可供参考
字典创建与删除
1、使用=将一个字典赋值给一个变量
>>> a= {'server': 'db.diveintopython3.org', 'database': 'mysql'}
>>> a
{'database': 'mysql', 'server': 'db.diveintopython3.org'}
>>> x = {} #空字典
>>> x
{}
2、使用 dict 根据给定的键、值创建字典
>>> d = dict(name='Dong', age=37)
>>> d
{'age': 37, 'name': 'Dong'}
3、使用 dict 利用已有数据创建字典
>>> keys = ['a', 'b', 'c', 'd']
>>> values = [1, 2, 3, 4]
>>> d= dict(zip(keys, values))
>>> d
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
>>> x = dict() #空字典
>>> x
{}
验证zip 和dictionary
4、以给定内容为键,创建值为空的字典
>>> a= dict.fromkeys(['name', 'age', 'sex'])
>>> a
{'age': None, 'name': None, 'sex': None}
可以使用del删除整个字典
>>> del a
字典元素的读取
以键作为下标可以读取字典元素,若键不存在则抛出异常
>>> aDict= {'name':'Dong', 'sex':'male', 'age':37}
>>> aDict['name']
'Dong'
>>> aDict['tel'] #键不存在,抛出异常
Traceback (most recent call last):
File "<pyshell#37>", line 1, in <module>
aDict['tel']
KeyError: 'tel'
使用字典对象的get方法获取指定键对应的值,并且可以在键不存在的时候返回指定值。
>>> print(aDict.get('address'))
None
>>> print(aDict.get('address', 'SDIBT'))
SDIBT
使用字典对象的items()方法可以返回字典的键、值对列表
使用字典对象的keys()方法可以返回字典的键列表
使用字典对象的values()方法可以返回字典的值列表
字典元素的读取(验证)
>>> a={'name':'Dong', 'sex':'male', 'age':37}
>>> for item in a.items(): #输出字典中所有元素
print(item)
('age', 37)
('name', 'Dong')
('sex', 'male')
>>> for key in a: #不加特殊说明,默认输出键
print(key)
age
name
sex
>>> for key, value in a.items(): #序列解包用法
print(key, value)
age 37
name Dong
sex male
>>> a.keys() #返回所有键
dict_keys(['name', 'sex', 'age'])
>>> a.values() #返回所有值
dict_values(['Dong', 'male', 37])
字典元素的添加与修改
当以指定键为下标为字典赋值时,若键存在,则可以修改该键的值;若不存在,则表示添加一个键、值对。
>>> a['age'] = 38 #修改元素值
>>> a
{'age': 38, 'name': 'Dong', 'sex': 'male'}
>>> a['address'] = 'SDIBT' #增加新元素
>>> a
{'age': 38, 'address': 'SDIBT', 'name': 'Dong', 'sex': 'male'}
使用字典对象的update方法将另一个字典的键、值对添加到当前字典对象
>>> a
{'name': 'Dong', 'sex': 'male', 'age': 38, 'address': 'SDIBT'}
>>> a.items()
dict_items([('name', 'Dong'), ('sex', 'male'), ('age', 38), ('address', 'SDIBT')])
>>> a.update({'test1':'test1','test2':'test2'})
>>> a
{'name': 'Dong', 'sex': 'male', 'age': 38, 'address': 'SDIBT', 'test1': 'test1', 'test2': 'test2'}
>>> aDict
{'age': 37, 'score': [98, 97], 'name': 'Dong', 'sex': 'male'}
>>> aDict.update({'a':'a','b':'b'})
>>> aDict
{'a': 'a', 'score': [98, 97], 'name': 'Dong', 'age': 37, 'b': 'b', 'sex': 'male'}
字典元素的删除
del删除
使用del删除字典中指定键的元素
>>> del a['test1']
>>> a
{'name': 'Dong', 'sex': 'male', 'age': 38, 'address': 'SDIBT', 'test2': 'test2'}
pop()方法删除
使用字典对象的pop()方法删除并返回指定键的元素
>>> a.pop('test2')
'test2'
>>> a
{'name': 'Dong', 'sex': 'male', 'age': 38, 'address': 'SDIBT'}
popitem()方法随机删除
使用字典对象的popitem()方法随机删除并返回字典中的一个元素,如果字典已经为空,却调用了此方法,就报出 KeyError 异常
>>> a.popitem()
('address', 'SDIBT')
>>> a
{'name': 'Dong', 'sex': 'male', 'age': 38}
clear()方法删除
使用字典对象的clear()方法来删除字典中所有元素
>>> a.clear()
>>> a
{}
字典推导式
{key表达式 : value表达式 for item in 容器 if 条件}
>>> s = {x:x.strip() for x in (' he ', 'she ', ' I')}
>>> s
{' he ': 'he', ' I': 'I', 'she ': 'she'}
>>> for k, v in s.items():
print(k, ':', v)
he : he
she : she
I : I
>>> {i:str(i) for i in range(1, 5)}
{1: '1', 2: '2', 3: '3', 4: '4'}
>>> x = ['A', 'B', 'C', 'D']
>>> y = ['a', 'b', 'b', 'd']
>>> {i:j for i,j in zip(x,y)}
{'A': 'a', 'C': 'b', 'B': 'b', 'D': 'd'}
>>> a = ['a', 'b', 'c', 'd', 'e']
>>> a1={k:v for k, v in enumerate(a)}
>>> a1
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'}
总结
字典的key一定是不可变的
字典种每个value的值都是通过hash算法来计算key得到的,如果key是可变的,每次计算得出的value结果都不同,那dict内部就完全混乱了。所以key的值一定是不可变的。
字典是无序的
(1)键值的哈希冲突,hash(key1) == hash(key2)时,向字典里连续添加的这个两个键的顺序是不可以控制的,也是无法做到连续的,后来的键会按算法调整到其它位置。
(2)字典空间扩容,当键的数量超过字典默认开的空间时,字典会做空间扩容,扩容后的键顺序和创建顺序就会发生变化,不受人为控制。
优势:查询速度快
不足:浪费空间
空间换时间