一.字典操作
1.往字典中添加键值对
- dict[“key”] = “value”
stu = {"name":"zhangsan","age":"18"} stu["sex"] = "boy" print stu
- setdefault()
stu = {"name":"zhangsan","age":"18"} stu.setdefault("sex") print stu #结果 {'age': '18', 'name': 'zhangsan', 'sex': None} stu = {"name":"zhangsan","age":"18"} stu.setdefault("sex","boy") print stu #结果 {'age': '18', 'name': 'zhangsan', 'sex': 'boy'}
2.替换字典中指定键的值
- dict[“key”] = “value”
stu = {"name":"zhangsan","age":18,"sex":"boy"} #替换值boy为gril stu["sex"] = "girl" print stu
3.update()一个字典所有项追加到另一个字典里
a = {"name":"zhangsan","sex":"boy"} b = {"age":18} a.update(b) #往字典a中追加字典b的内容 print a print b
4.字典取值
- get()函数 –> 当提取的键不存在时,不会报错,为空
a = {"name":"zhangsan","sex":"boy"} print a.get("name") #当取的键不存在时,不报错,返回值为None print a.get("age")
- dict[“key”]
a = {"name":"zhangsan","sex":"boy"} print a["name"]
5.keys()从字典中取出所有键
- 不能通过在括号中输入键来取键值
- 返回的是一个键列表
a = {"name":"zhangsan","sex":"boy","age":18} print a.keys() #返回所有键列表
6.values() 从字典中取出所有值
- 返回的是一个值列表
a = {"name":"zhangsan","sex":"boy","age":18} print a.values() #返回所有值列表
7.del() 删除键值对
a = {"name":"zhangsan","sex":"boy","age":18} del a["name"] print a #结果中"name":"zhansan"该键值对全部被删除
8.pop()删除键值对
- 括号中必须为键且不能为空
- 返回值为删除键的值
a = {"name":"zhangsan","sex":"boy","age":18} value = a.pop("name") print value #返回值为"zhangsan" print a #字典a中的"name":"zhangsan"键值对被删除
9.popitem()随机删除键值对
- 并返回该键值对的元组
a = {"name":"zhangsan","sex":"boy","age":18} b = a.popitem() print b #返回值为包含被删除的键值对的一个元组 print a #字典a中的某个键值对被删除
10.clear()清空字典中的键值对
- 没有返回值
- 原字典为空字典{}
a = {"name":"zhangsan","sex":"boy","age":18} a.clear() print a
11.copy()复制创建字典
a = {"name":"zhangsan","sex":"boy","age":18} b = a.copy() print b #b是a复制出来的字典
12.has_key()检查字典是否有指定的键,有结果为 True,没有结果为 False
a = {"name":"zhangsan","sex":"boy","age":18} print a.has_key("age") #True print a.has_key("height") #False
user = raw_input("账号:") pwd = raw_input("密码:") mysql.setdefault(user,pwd) print mysql if mysql.has_key(user): print "ok" else: print "no"