删除
del
>>> people = {‘kind‘: ‘beauty‘, ‘age‘: ‘22‘} >>> del people[‘age‘] >>> people {‘kind‘: ‘beauty‘}
pop
>>> people = {‘kind‘: ‘beauty‘, ‘age‘: ‘22‘} >>> people.pop(‘age‘) ‘22‘ >>> people {‘kind‘: ‘beauty‘}
popitem 删除一个,不带参数(字典是无序的,不确定会删除哪个)
>>> people = {‘kind‘: ‘beauty‘, ‘age‘: ‘22‘} >>> people.popitem() (‘kind‘, ‘beauty‘) >>> people {‘age‘: ‘22‘}
增、改
setdefault 如果不存指定键在就新增,存在不做任何操作
>>> people = {‘kind‘: ‘beauty‘, ‘age‘: ‘22‘} >>> people.setdefault(‘like‘, ‘sport‘) ‘sport‘ >>> people {‘kind‘: ‘beauty‘, ‘like‘: ‘sport‘, ‘age‘: ‘22‘} >>> people.setdefault(‘kind‘, ‘fool‘) ‘beauty‘ >>> people {‘kind‘: ‘beauty‘, ‘like‘: ‘sport‘, ‘age‘: ‘22‘}
update 很常用,直接修改或新增
查
get 没取到为None(也可设置为其它)
>>> people = {‘kind‘: ‘beauty‘, ‘age‘: ‘22‘} >>> like = people.get(‘like‘) >>> like >>> print like None
in 是否存在该键(Python2里还有has_key也是相同用法,Python3里没有has_key)
>>> people = {‘kind‘: ‘beauty‘, ‘age‘: ‘22‘} >>> print ‘kind‘ in people True
>>> people = {‘kind‘: ‘beauty‘, ‘age‘: ‘22‘} >>> print(‘age‘in people) True
其它操作
items 转换为字典
>>> people {‘kind‘: ‘beauty‘, ‘like‘: ‘sport‘, ‘age‘: ‘22‘} >>> people.items() dict_items([(‘kind‘, ‘beauty‘), (‘like‘, ‘sport‘), (‘age‘, ‘22‘)])
fromkeys 创建字典,所有的键共用一个值(修改一个,其它的都变,像浅copy)
>>> like = dict.fromkeys([‘sport‘, ‘singing‘, ‘dance‘], ‘666‘) >>> like {‘singing‘: ‘666‘, ‘sport‘: ‘666‘, ‘dance‘: ‘666‘} >>> like[‘singing‘] = ‘yes‘ >>> like {‘singing‘: ‘yes‘, ‘sport‘: ‘666‘, ‘dance‘: ‘666‘} >>> lau = dict.fromkeys([‘C‘, ‘Java‘, ‘Python‘], [‘code‘, ‘yes‘]) >>> lau {‘C‘: [‘code‘, ‘yes‘], ‘Python‘: [‘code‘, ‘yes‘], ‘Java‘: [‘code‘, ‘yes‘]} >>> lau[‘Python‘][1] = ‘no‘ >>> lau {‘C‘: [‘code‘, ‘no‘], ‘Python‘: [‘code‘, ‘no‘], ‘Java‘: [‘code‘, ‘no‘]}