字典
字典是无序、可变序列。
定义字典时,每个元素的键和值(key=>value)用冒号分隔,元素之间用逗号分隔,所有的元素放在一对大括号“{}”中。
字典中的键可以为任意不可变数据,比如数字、字符串、元组。
globals()返回包含当前作用域内所有全局变量和值的字典
locals()返回包含当前作用域内所有局部变量和值的字典
字典创建
使用=将一个字典赋值给一个变量
>>> a_dict = {‘name’: ‘Alice’,’age’:18}
>>> a_dict
{‘name': ‘Alice', ‘age’: 18}
>>> x = {} #空字典
>>> x
{}
使用dict利用已有数据创建字典
>>> keys = ['a', 'b', 'c', 'd']
>>> values = [1, 2, 3, 4]
>>> dictionary = dict(zip(keys, values))
>>> dictionary
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
>>> x = dict() #空字典
>>> x
{}
使用dict根据给定的键、值创建字典
>>> d = dict(name='Dong', age=37)
>>> d
{'age': 37, 'name': 'Dong'}
以给定内容为键,创建值为空的字典
>>> adict = dict.fromkeys(['name', 'age', 'sex'])
>>> adict
{'age': None, 'name': None, 'sex': None}
可以使用del删除整个字典
字典元素的读取
以键作为下标可以读取字典元素,若键不存在则抛出异常
>>> aDict = {'name':'Dong', 'sex':'male', 'age':37}
>>> aDict['name']
'Dong'
>>> aDict['tel'] #键不存在,抛出异常
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
aDict['tel']
KeyError: 'tel'
使用字典对象的get方法获取指定键对应的值,并且可以在键不存在的时候返回指定值。
>>> print(aDict.get('address'))
None
>>> print(aDict.get('address', 'SDIBT'))
SDIBT
>>> aDict['score'] = aDict.get('score',[])
>>> aDict['score'].append(98)
>>> aDict['score'].append(97)
>>> aDict
{'age': 37, 'score': [98, 97], 'name': 'Dong', 'sex': 'male'}
使用字典对象的items()方法可以返回字典的键、值对
使用字典对象的keys()方法可以返回字典的键
使用字典对象的values()方法可以返回字典的值
>>> aDict={'name':'Dong', 'sex':'male', 'age':37}
>>> for item in aDict.items(): #输出字典中所有元素
print(item)
('age', 37)
('name', 'Dong')
('sex', 'male')
>>> for key in aDict: #不加特殊说明,默认输出键
print(key)
age
name
sex
字典元素的添加与修改
当以指定键为下标为字典赋值时:
1)若键存在,则可以修改该键的值;
2)若不存在,则表示添加一个键、值对。
>>> aDict['age'] = 38 #修改元素值
>>> aDict
{'age': 38, 'name': 'Dong', 'sex': 'male'}
>>> aDict['address'] = 'SDIBT' #增加新元素
>>> aDict
{'age': 38, 'address': 'SDIBT', 'name': 'Dong', 'sex': 'male'}
使用字典对象的update()方法将另一个字典的键、值对添加到当前字典对象。
>>> 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删除字典中指定键的元素
使用字典对象的clear()方法来删除字典中所有元素
使用字典对象的pop()方法删除并返回指定键的元素值
使用字典对象的popitem()方法删除并返回字典中的一个元素
有序字典
Python内置字典是无序的,如果需要一个可以记住元素插入顺序的字典,可以使用collections.OrderedDict。
>>> x = dict() #无序字典
>>> x['a'] = 3
>>> x['b'] = 5
>>> x['c'] = 8
>>> x
{'b': 5, 'c': 8, 'a': 3}
>>> import collections
>>> x = collections.OrderedDict() #有序字典
>>> x['a'] = 3
>>> x['b'] = 5
>>> x['c'] = 8
>>> x
OrderedDict([('a', 3), ('b', 5), ('c', 8)])
字典推导式
>>> {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'}
字典方法
方法 | 说明 |
dict.clear() | 删除字典内所有元素 |
dict.copy() | 返回字典的浅复制 |
dict.fromkeys(seq[, val]) | 创建一个新字典,以序列 seq 中元素做字典的键,val 为字典所有键对应的初始值 |
dict.get(key, default=None) | 在列表lst中删除首次出现的指定元素 |
dict.has_key(key) | 如果键在字典dict里返回true,否则返回false |
dict.items() | 以列表返回可遍历的(键, 值) 元组数组 |
dict.keys() | 以列表返回一个字典所有的键 |
dict.setdefault(key, default=None) | 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default |
dict.update(dict2) | 把字典dict2的键/值对更新到dict里 |
dict.values() | 以列表返回字典中的所有值 |
pop(key[,default]) | 删除字典给定键 key 所对应的值,并返回。如果key不存在,则返回default值。 |