python基础数据类型dict
dict:用{}括起来,以键值对的形式存储的容器性数据类型
dic={'name';'jackma','age':18}
dict的键必须要不可变的数据类型:int、str
字典在python3.7版本后是有序的
字典的优点:查询速度非常快,存储关联型数据
字典的缺点:占用空间大,以空间换时间
字典的创建方式
dic = dict((('one',1),('two',2),('three',3))) print(dic) # {'one': 1, 'two': 2, 'three': 3} dic1 = dict({'one':1,'two':2,'three':3}) dic2 = dict(one=1,two=2,three=3) print(dic2) # {'one': 1, 'two': 2, 'three': 3}
字典的增加,改
dic = {'name':'jack','age':20} dic['sex'] = 'male' #如果有sex这个键,就替换值,如果没有sex,就增加键值对 print(dic) dic = {'name':'jack','age':20} # seldefault:没有键,就添加键值对,没有指定值,就默认添加值为None,有这个键值对,就不改变 dic.setdefault('sex') # {'name': 'jack', 'age': 20, 'sex': None} dic.setdefault('sex','male') #{'name': 'jack', 'age': 20, 'sex':'male'} dic = {'name':'jack','age':20} dic1 = {'name':'tony','age':30,'sex':'male'} # update dic.update(job='ceo') # 增加键值对 dic.update(name='robin') # 修改值 dic.update([(1,'a'),(2,'b'),(3,'c')])# 利用元祖拆包,增加键值对{'name':'jack','age':20, 1: 'a', 2: 'b', 3: 'c'} dic.update(dic1) # 覆盖增加,将重复的键对应的值修改,没有的键值对就直接增加 # fromkeys dic = dict.fromkeys('abc',10) print(dic) # {'a': 10, 'b': 10, 'c': 10} dic = dict.fromkeys([1,2,3],100) print(dic) # {'a': 10, 'b': 10, 'c': 10} dic = dict.fromkeys([1,2,3],['a','b','c']) print(dic) # {1: ['a', 'b', 'c'], 2: ['a', 'b', 'c'], 3: ['a', 'b', 'c']} dic = dict.fromkeys([1,2,3],[]) dic.[1].append(666) print(dic) # {1: [666], 2: [666], 3: [666]}
字典的删除
# pop:通过key删除字典的键值对,有返回值,可设置返回值 dic = {'name':'jack','age':20} print(dic.pop('name'),dic) # jack {'age': 20} dic = {'name':'jack','age':20} print(dic.pop('sex','no key')) # 当指定删除的key,不再dic中,就会返回指定的内容,这里返回no key # clear:清空字典 dic = {'name':'jack','age':20} dic.clean() print(dic) # {} # del:通过key删除键值对,可以删除整个字典 dic = {'name':'jack','age':20} del dic['name'] print(dic) # {'age': 20} del dic # 循环删除字典中的键值对 dic = {'k1':2,'k2':3,'k3':4,'age':20} for i in dic.keys(): dic.pop(i) print(dic) # 这种写法会报错,因为循环的是字典的键,当删除了一个键值对后,字典就变了,循环体就变了 #正确写法 dic = {'k1':2,'k2':3,'k3':4,'age':20} l = list(dic.keys()) for i in l: dic.pop(i) print(dic) # {}
字典的查询
dic = {'name':'jack','age':20,'job':'networker'} print(dic['name']) # 这种方式,当key不存在时,就会报错 print(dic.get('name','no key')) # 当key不存在时,就返回设置的内容 dic = {'name':'jack','age':20,'job':'networker'} print(dic.keys()) # dict_keys(['name', 'age', 'job']) print(list(dic.keys())) # ['name', 'age', 'job'] print(dic.values()) # dict_values(['jack', 20, 'networker']) print(list(dic.values())) # ['jack', 20, 'networker'] dic = {'name':'jack','age':20,'job':'networker'} print(dic.items()) #dict_items([('name', 'jack'), ('age', 20), ('job', 'networker')]) print(list(dic.items())) # [('name', 'jack'), ('age', 20), ('job', 'networker')] for key,value in dic.items(): print(key,value)