3-3 字典
1、字典的定义
1 stu_info = {"name":"王志华","age":18,"addr":"北京"} 2 # key - value
2、查询
1 #查 2 print(stu_info) 3 print(stu_info['name']) 4 print(stu_info['age']) 5 print(stu_info['money']) #取key不存在的 KeyError: 'money'
3、修改元素
1 stu_info = {"name": "王志华", "age": 18, "addr": "北京"} 2 #修改 3 stu_info['addr'] ='上海' 4 print(stu_info)
4、新增字典元素
1 stu_info = {"name": "王志华", "age": 18, "addr": "北京"} 2 #新增 3 stu_info['phone'] = 1234567 4 stu_info.setdefault('email','sfsfs@163.com') 5 #你用setdefault新增一个已经存在的key,它不会改变原来key的value 6 stu_info.setdefault('age',29) 7 print(stu_info) 8 #{'name': '王志华', 'age': 18, 'addr': '北京', 'phone': 1234567, 'email': 'sfsfs@163.com'}
5、删除字典元素
1 stu_info = {"name": "王志华", "age": 18, "addr": "北京"} 2 #删除 3 stu_info.pop('addr') 4 del stu_info['age'] # 5 stu_info.clear() #清空这个字典 6 stu_info.popitem()#从字典里面随机删除一个元素 7 print(stu_info)
6、合并两个字典
1 stu_info = {"name": "王志华", "age": 18, "addr": "北京"} 2 #删除 3 stu_info.pop('addr') 4 del stu_info['age'] # 5 stu_info.clear() #清空这个字典 6 stu_info.popitem()#从字典里面随机删除一个元素 7 print(stu_info)
8 #{'b': 1, 'a': 'v'}
7、获取字典中所有的key值和value值
1 stu_info = {"name": "王志华", "age": 18, "addr": "北京"} 2 print(stu_info.keys()) #获取字典里面所有的key 3 # dict_keys(['name', 'age', 'addr']) 4 print(stu_info.values()) #获取字典里面所有的value 5 # dict_values(['王志华', 18, '北京'])
8、循环字典,每次循环的是字典的key
1 stu_info = {"name": "王志华", "age": 18, "addr": "北京"} 2 #直接循环字典,看看每次循环的是字典的key 3 for i in stu_info: 4 print(i,stu_info[i])
循环字典,每次循环的是字典的key,也可以打印出对应的value值
1 stu_info = {"name": "王志华", "age": 18, "addr": "北京"} 2 #直接循环字典,看看每次循环的是字典的key 3 for i in stu_info: 4 # print(i,stu_info[i]) 5 s = " %s => %s" % (i, stu_info.get(i)) 6 print(s)
7 # name => 王志华
8 # age => 18
9 # addr => 北京
1 stu_info = {"name": "王志华", "age": 18, "addr": "北京"} 2 print(stu_info.items()) 3 4 for k,v in stu_info.items(): 5 print(" %s => %s" %(k,v))
9、判断key是否存在
1 stu_info = {"name": "王志华", "age": 18, "addr": "北京"} 2 print('name' in stu_info) #判断key是否存在 3 print('name' in stu_info.keys())#判断key是否存在