python---字典
1、字典的声明
dic = {'dog':'wang','cat':'miao','count':3}
2、字典删除
删除某个键值对
dic = {'dog':'wang','cat':'miao','count':3} list1 = [1,2,3] dic.pop('count') #与列表不同,要跟pop的key值 print(dic) list1.pop() #列表的pop是删除列表末尾的值 print(list1)
删除全部
dic = {'dog':'wang','cat':'miao','count':3} dic.clear() print(dic) 控制台输出:{}
3、fromkeys,把列表的元素作为字典的key值
lis = ['dog','cat','snake'] dic = {} dic = dic.fromkeys(lis,'animal') print(dic) 控制台输出:{'cat': 'animal', 'dog': 'animal', 'snake': 'animal'}
4、zip:将两个列表组为字典
lis = ['dog','cat','snake'] lis2 = [1,2,3] m = dict(zip(lis,lis2)) print(m) 控制台输出结果:{'dog': 1, 'cat': 2, 'snake': 3}
5、get,安全的取字典的值,取不到不会抛异常,同时可以设置默认值
dic = {'dog':'wang','cat':'miao','count':3} print(dic['haha']) 控制台输出结果:KeyError: 'haha' #取不到值时会报错 dic = {'dog':'wang','cat':'miao','count':3} print(dic.get('hahaha')) #安全的取值,取不到时,没设置默认值返回None print(dic.get('hahaha',1)) #设置了默认值时,取不到返回默认值 print(dic.get('dog',2)) #设置了默认值,取到值返回取到的值 控制台输出结果:None 1 wang
6、in:python中判断某个值,判断的是key值,不包括value值
dic = {'dog':'wang','cat':'miao','count':3} print('dog' in dic) print('wang' in dic) 控制台输出:True False
7、keys、values、items
dic = {'dog':'wang','cat':'miao','count':3} keys = dic.keys() values = dic.values() items = dic.items() print("keys:{0}, values:{1}, items:{2}".format(keys,values,items) ) 控制台输出:keys:dict_keys(['cat', 'count', 'dog']), values:dict_values(['miao', 3, 'wang']), items:dict_items([('cat', 'miao'), ('count', 3), ('dog', 'wang')])
dic = {'dog':'wang','cat':'miao','count':3} for item in dic.items(): #也可用dic.keys()、dic.values()分别取到key和value的值 key,value = item print('key:{0} ,value:{1}'.format(key,value)) 控制台输出: key:dog ,value:wang key:cat ,value:miao key:count ,value:3
8、字典的新增 和 修改
dic = {'dog':'wang','cat':'miao','count':3} dic.setdefault('dog',666) # 存在该键值,直接对值进行了修改 dic.setdefault('name','lisa') #不存在该键值,则添加 print(dic) 控制台输出:{'dog': 'wang', 'cat': 'miao', 'count': 3, 'name': 'lisa'}
dic = {'dog':'wang','cat':'miao','count':3} dic['dog'] = 'hahaha' #存在该键值,直接对值进行了修改 dic['name'] = 'lisa' #不存在该键值,则添加 print(dic) 控制台输出:{'count': 3, 'name': 'lisa', 'dog': 'hahaha', 'cat': 'miao'}
9、
10、
11、